Passing data from MVC Controller to View in PHP Passing data from MVC Controller to View in PHP php php

Passing data from MVC Controller to View in PHP


I'm going to recommend the concept of Fat Models, Skinny Controllers (or, Fat Models Thin Controllers if you prefer...)

In otherwords, your model is too strict - tying your model to represent only something like a RowDataGateway is extremely limiting.

In fact, I think good models hide the fact that you're reading the data from a database at all. Because, in reality, your data could be in text files, or from a web service, or whatever. If you treat your Model like nothing more than a glorified DBAL, you doom yourself to having tightly-coupled code in your controllers that just won't let you break away from the "data only comes from the database" way of thinking.


I've seen both of the first two methods implemented in popular MVC/templating frameworks.

django uses the first method, passing to the view a dictionary of variables which the view uses to fill the template.

smarty uses the second method, creating a Smarty object and assigning values to each the properties in the container.

Your third method seems to essentially be the same as the second, with minor architecture differences.

Really, I guess I haven't said anything that you haven't thought of already. Basically, these are all sounds ideas, so implement whatever you feel you are most comfortable with.


In the one I use, it has automatically has a view property in the controller that you can access methods and properties on the view. All public properties are then accessible within the view view '$this' since the view is rendered in it's own objects context.

In the controller:

$this->view->myVar = 'test';

And in the view:

$this->myVar; // 'test'

The same goes for the layout since the are both separate instances of the same view object:

$this->layout->myVar = 'test';

And then in the layout:

$this->myVar; // 'test'

The framework used to be proprietary, but is about to be released to the general public. I'd be happy to send you some code from it if you think that'd help. Remember, the simplest answer is usually the best answer.