Separation of presentation and business logic in PHP

痴心易碎 提交于 2019-12-05 09:00:18
Josh K

Never echo out HTML with PHP. Instead write it inline (without evil short tags) as

<tr class="<?php echo $myclass; ?>">

Other options for helping to separate out the logic / view would be to use a PHP Framework like CodeIgniter.

I would ditch the book and instead focus more on learning core PHP skills like functions, classes, etc. Then start playing the the several popular frameworks out there.

As a side note: The thing I do not understand is that in most example code, if some database query or whatnot gives an error, there is always:

That's because they are displaying the errors incorrectly. You should either store the errors in a sesssion and then display them on the page (clearing them as well) or throw them into the error log with the error_log function. error_log("Something happened in MyClass");

The thing I haven't figured out is how could I do this "do logic first, then presentation" thing so that I would not have to replicate for example the navigation logic and navigation presentation in all of the pages.

Think of things in a MVC approach. You call the controller (logic) first. It figures out what is needed. If it needs data from the database it invokes a Model and requests it. Then it formats it, adds other data, runs additional queries, and then passes it to the view.

sound like a template engine is what you are looking for - ask google for a lot of results. personally, i like smarty very much.

(and throw away that book, sound like it's... old)

MVC (Model View Controller) sounds like it might suit your needs. You can read about that here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!