How to set Layout using Plugin in Zend FrameWork

By | January 27, 2014

Some time we need to set different layout based on user type. So the best way to handle it by using plugin.

Bootstrap.php:

1
2
3
4
5
6
7
8
9
10
11
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    public function _initPlugins()
    {
        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Zend_Controller_Plugin_Acl()); // Plugin file path library/zend/controller/Plugin/Acl.php
    }
}
?>

In library/zend/controller/Plugin/Acl.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch()
    {
        $user = Zend_Auth::getInstance();
        $role = $user->getIdentity()->role;
        $layout = Zend_Layout::getMvcInstance();

        switch ($role) {
            case 'admin':
                $layout->setLayout('layout1');
                break;

            case 'user':
                $layout->setLayout('layout2');
                break;

            default:
                $layout->setLayout('layout');
                break;
        }
    }
}
?>

Hope! you will enjoy.

Leave a Reply