Reputation: 10033
I have created a Zend Framework website and I'm now updating it to switch out the layout file depending on whether or not the user is on a mobile device.
I have written a class to deal with the detection but I don't know where is best to place this check and also trigger the layout file being used.
Code:
include(APPLICATION_PATH . "/classes/MobileDetection.php");
$detect = new MobileDetect();
if ($detect->isMobile()) {
$layout = $layout->setLayout('mobile');
}
I can trigger the layout from the Bootstrap function _initViewHelpers()
but I get a 500 error as soon as I add the include line above.
Any recommendation on how and where to place this? I originally has a helper that dealt with the check but that was used in the layout itself rather than enabling me to swap the whole layout file out.
Upvotes: 2
Views: 641
Reputation: 1926
Imagine you have www.example.com and when you hit this page with a mobile device you want to be redirected to mobile.example.com:
knowing that www is a module and mobile is a module in the application with different layouts
I found following page on how to detect a mobile device http://framework.zend.com/manual/de/zend.http.user-agent.html#zend.http.user-agent.quick-start
How and where to redirect?
Regards
Upvotes: 0
Reputation: 16
Actually what really going on is that you have one new separate module called "mobile" and the layout plugin helper actually is doing the preDispatch() method checking if this is the module called. After that the method is changing the layout. It's quite complicated. I think you can actually made a base controller for your mobile version and in its init() method to change the layout with $this->_helper->layout->changeLayout().
Upvotes: 0
Reputation: 342695
You can use a plugin, that's what I do:
<?php
class Mobile_Layout_Controller_Plugin_Layout extends Zend_Layout_Controller_Plugin_Layout
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
switch ($request->getModuleName()) {
case 'mobile': $this->_moduleChange('mobile');
}
}
protected function _moduleChange($moduleName) {
$this->getLayout()->setLayoutPath(
dirname(dirname(
$this->getLayout()->getLayoutPath()
))
. DIRECTORY_SEPARATOR . 'layouts/scripts/' . $moduleName
);
$this->getLayout()->setLayout($moduleName);
}
}
I keep it in library/ProjectName/Layout/Controller/Plugin/Layout.php
.
In your Bootsrap, you will need to incorporate something like this:
Zend_Layout::startMvc(
array(
'layoutPath' => self::$root . '/application/views/layouts/scripts',
'layout' => 'layout',
'pluginClass' => 'Mobile_Layout_Controller_Plugin_Layout'
)
);
It actually took me a while to get this figured out, but once you work through it, you will be so much happier. Hope that helped :)
Upvotes: 2