We want to implement a method to completely switch layout of our Zend Framework application without loosing flexibility. The solution must give us the possibility of switching all layouts and the views of the controllers we want.
I found some solutions on the Web, but I decided to post this article because no one satisfies my needs. They all resort to ContextSwitch to handle views file names, but, in my applications, I just use ContextSwitch in some actions for other purpose, so I’m unable to apply them without restructure existing code.
In my implementation I decided to use Zend_Inflector to remap layouts and views file names and give, in this way, the possibility of having a different file for each device the developer wants (desktop, mobile, tablet, etc.). The result for layouts will be a structure like this:
While for each controller the developer decides to involve, the structure will be:
I assume you have a valid instance of Zend_Http_UserAgent object in your application.
First of all, we need a controller plugin to switch layouts. Let’s create a new file in /library/App/Controller/Plugin called DeviceLayout.php to put the following code into:
Now to activate the plugin, add the following line in your application.ini config file:
resources.frontController.plugins.devicelayout = "App_Controller_Plugin_DeviceLayout"
By this point, every time your application will be accessed by mobile or tablet device, the layout will be switched to layout.mobile.phtml or layout.tablet.phtml.
To handle views, instead, we have to edit each controller we want to support devices and add the following code:
At this point each to different device will be shown a different view like index.phtml, index.mobile.phtml or index.table.phtml.
Following this article we implemented a flexible solution to switch between different layouts in our Zend Framework application, preserving all other functionalities (specially ContextSwitch). Now all you need to do in implements your new layouts and views!
Of course, all comments are welcome. Obviously, I know that the code can be improved by adding more functionalities, refactoring, etc., but what I would like to analyse and discuss, are the possible limitations of this approach.