Wednesday 29 April 2009

Change to the view layer

One thing that really frustrates me about all the PHP frameworks out there is that they force you to run the view functions yourself. It's not so much MVC as it is "DIYC".

100% of the time you will want to send output to the browser. Hyperbolically speaking, 99% of the time you will want to send the browser a Web page. Now, if you take the approach that your "View" layer (in MVC) is just a templating library, then I can see how you would want to separate out sending random HTTP headers to the browser from your templating system. But, if your concept of a "View" layer handles all the output to the browser (or whatever client happens to be requesting your service) then it is silly to force each controller action to specify and call the output function.

In Magento you can see this code repeated all over the place:

$this->loadLayout();
$this->renderLayout();

A quick grep reveals this bit of code repeated 230 times in the Magento source. But this sort of thing also happens in Code Igniter with the code $this->template().

If the actions or events get called for you automatically by the front controller, why not the template too? Having your output functions called automatically saves repetitive coding and forces a clearer separation between business logic and display logic. In addition to that, it reduces the function stack size by one.

So, I have moved the loadLayout and renderLayout responsibilities up, out of the controller actions to a higher level. For the rare occasion when you need to redirect or show a different output, you can specify a custom output handler with $this->outputHandler = 'myfunction'. If this flag in the controller actions is left alone, then the standard loadLayout() renderLayout() pair is called for you.

1 comment:

Josh said...

Magento should have solved this with the ZF view renderer. They simply do not refactor their code.