佳音的博客

2007/05/16

Implementing MVC in PHP: The View

Filed under: Uncategorized — 佳音 @ 10:39 上午

Implementing MVC in PHP: The View

by Joe Stump
01/26/2006

This is the third article in a series about understanding MVC in PHP. The first article explained basics of MVC programming in PHP. The second article showed the implementation of the Controller in MVC. The final article is Implementing MVC in PHP: The Model.

Click here to find out more!

The presentation layer, as I call it, is the View, in common MVC terms. Its sole responsibility is to display information. It could care less about authenticating users, what the data is or, for the most part, where it came from. The only thing it has to worry about is how to render it and where to send it once rendered.

By default, the framework uses Smarty to render the framework. I’m not here to argue semantics, but your presentation layer should consist of a template engine of some sort and a few supporting presentation layers.

The idea is that, after the Model runs, the framework hands it off to a child of the FR_Presenter_common class. Actually, the framework uses the FR_Presenter::factory() to create the presenter. Each presenter should have a display() method that does the actual rendering. When the factory creates the presenter, it passes the presenter the instance of the model class. The presenter then gets the model’s data using its getData() method. From there, the presenter is free to present that data however it sees fit.

FR_Presenter_smarty

The way I’ve created my Smarty presenter is a hybrid of two templates. I create a Smarty template, and the outer page template includes the model’s template. The model class’s $pageTemplateFile can request a particular outer template. If it does not, the default is tpl/default/templates/page.tpl. The page.tpl template then uses the {$modulePath} and {$tplFile} directives to include the model’s template. All model templates should reside in modules/example/tpl/.

After assigning the variables, the controller runs Smarty’s display function to render the templates. With little modification, you could wrap these calls with Smarty’s built-in caching as well. By using Smarty, you could enable an output modifier to output gzipped code instead of plain HTML.


	

Powered by 00RZ