Context Switching Layouts with the Zend Framework
Wed Jul 23, 2008 at 13.31
If you have not been hiding under a rock for the past few years, you realize that there are many different platforms and mediums to which a web site or application might wish to publish. The guys at Zend came up with a tool that can be used to facilitate multiple device view rendering in a semi-transparent way. This is known as Context Switching in the Zend Framework and is accomplished using the ContextSwitch Action Helper.
One hurdle I came across was figuring out a simple way to provide a consistent user experience through what is known as a two-stage view rendering. This is done using Zend_Layout. However, layouts written in standard XHTML won't really work well for our mobile platform, and likewise for XHTML-MP in a browser on a PC. Enter in context switching. First we are going to set up our context switching inside the index controller:
{
public function init()
{
$context = $this->_helper->getHelper('contextSwitch');
$context->addContext('mobile', array('suffix' => 'mobile'))
->setAutoDisableLayout(false)
->addActionContext('index', 'mobile')
->initContext();
}
public function indexAction()
{
//do something here, it's unimportant for this post
}
}
This will allow us to have a mobile view for urls such as http://example.com/index/index/format/mobile (NOTE: this should be prettier, but routing is outside the scope of this post). The key to take from this short code sample is the setAutoDisableLayout(false) bit.
Now, assuming we have created a view script called index.mobile.phtml we will now see the contents of the mobile view script dumped inside the default layout script. This isn't exactly what we wanted, believe it or not. Well, not really what we wanted but it's pretty close. We just need to tell the Layout manager that we want a contextual layout as well as a contextual view script. We do that using the layout helper:
{
$context = $this->_helper->getHelper('contextSwitch');
$context->addContext('mobile', array('suffix' => 'mobile'))
->setAutoDisableLayout(false)
->addActionContext('index', 'mobile')
->initContext();
$layout = $this->_helper->getHelper('layout');
$currentContext = $context->getCurrentContext();
if($currentContext)
{
$layout->setLayout($layout->getLayout() . "." . $currentContext);
}
}
After we have a new layout script called layout.mobile.phtml we should be good to go.
References
Zend Framework: ContextSwitch Action Helper
Zend Framework: Layout Configuration Options (see: getLayout())
- Tagged:
- technicalarticles
- php
- Zend Framework









