Understanding MVC Views in PHP

后端 未结 7 690
生来不讨喜
生来不讨喜 2020-11-22 10:45

I have to seem problems grasping the concept of Views in MVC, they are, according to what I\'ve read, the layer that manages the presentation in the aplication, but many of

7条回答
  •  情话喂你
    2020-11-22 11:13

    The second tutorial is the way that Code Igniter framework works, and the one which I am used to. I follow it even when using no framework at all.

    In fact, the developer must put the MVC-like principles in practice, otherwise he/she can make the lasagne or spaghetti even using the most MVC-like oriented framework.

    Using the "PHP file as view template" approach, ideally one would use minimum PHP statements, basically only for repeat-structures (foreach ($array as $item)), basic conditionals (if ($boolean)) and echo - as if it was, indeed, a template language, and nothing more.

    So, the tags in the view template files should be merely placeholders, and nothing else.

    No database queries, access to the model, calculations, and the like should be performed in the view template file. It should be treated, basically, as an HTML file with placeholders. (With its associated CSS and JavaScript. Things may got more complex when the application relies on JavaScript / AJAX a lot...)

    Following these simple principles, we effectively do some separation of the presentation from the business logic. Even sounding so simple, I'm tired of dealing with Code Igniter code which does not follow it. Some use "helper functions" to disguise the model/database calls - and think it is a good practice! :-)

    You don't see a require inside these PHP view template files because they are required instead, from the "view building" methods.

    Of course, one should not echo and/or print from inside the controller and model functions. This is also very simple, but I am also tired to see spaghetti code echoing out HTML from inside CI controller methods.

    In practice, the controller calls the model methods, build all the necessary data for the view, and as a last step, calls the view (i.e., builds and output it), passing the already previously obtained data to it.

    Makes sense? I don't know if I answered your question. At least, these are my "2 cents".

提交回复
热议问题