Zend Framework – quick tutorial (part 3) – front controller plugins

Why writing a front controller plugin?

Almost every application uses a database connection and acl module. Why doing this in the bootstrap and to mantain many lines of code there, instead of making it clear and mantainable. Of course you can have all these lines of code in your bootstrap, but you know for serious applications that recently will become an obstacle. That’s why Zend Framework allows you to use Front_Controller plugin.

First in you bootstrap add those lines of code

/*
 * add a simple plugin to the controller
 */
 
$front->registerPlugin(new Zend_Controller_Plugin_Init())
      ->registerPlugin(new Zend_Controller_Plugin_Acl());

These two classes (Zend_Controller_Plugin_Init and Zend_Controller_Plugin_Acl) should be placed in two different files with the same names in Controller/Plugins directory under Zend folder, and garantee you that both classes will be instanciated before starting the front controller.

There is the example of Zend_Controller_Plugin_Init:

<?php
 
/** Zend_Acl */
require_once 'Zend/Acl.php';
 
/** Zend_Controller_Plugin_Abstract */
require_once 'Zend/Controller/Plugin/Abstract.php';
 
/**
 * Front Controller Plugin
 */
final class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
 
/**
 * @var Zend_Acl
 **/
protected $_acl;
 
/**
 * @var string
 **/
protected $_roleName;
 
/**
 * @var array
 **/
protected $_errorPage;
 
/**
 * Constructor
 *
 * @param mixed $aclData
 * @param $roleName
 * @return void
 **/
public function __construct()
{
 
// define the error controller
$this->_errorPage = array('module' => 'default', 'controller' => 'error',
    'action' => 'denied');
 
$this->_roleName = 'defaultRole';
// if (null !== $this->_acl) {
$this->_initAcl();
// }
 
}
 
/**
 * Returns the ACL object
 *
 * @return Zend_Acl
 **/
public function getAcl()
{
    return $this->_acl;
}
 
/**
 * Sets the ACL role to use
 *
 * @param string $roleName
 * @return void
 **/
public function setRoleName($roleName)
{
    $this->_roleName = $roleName;
}
 
/**
 * Returns the ACL role used
 *
 * @return string
 * @author
 **/
public function getRoleName()
{
    return $this->_roleName;
}
 
/**
 * Sets the error page
 *
 * @param string $action
 * @param string $controller
 * @param string $module
 * @return void
 **/
public function setErrorPage($action, $controller = 'error', $module = null)
{
$this->_errorPage = array('module' => $module,
    'controller' => $controller,
    'action' => $action);
}
 
/**
 * Returns the error page
 *
 * @return array
 **/
public function getErrorPage()
{
    return $this->_errorPage;
}
 
/**
 * Predispatch
 * Checks if the current user identified by roleName has rights to the requested url (module/controller/action)
 * If not, it will call denyAccess to be redirected to errorPage
 *
 * @return void
 **/
 
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
    $resourceName = '';
    if ($request->getModuleName() != 'default') {
    $resourceName .= $request->getModuleName() . ':';
}
 
$resourceName .= $request->getControllerName();
 
/** Check if the controller/action can be accessed by the current user */
if (!$this->getAcl()->isAllowed($this->_roleName, $resourceName, $request->getActionName())) {
 
/** Redirect to access denied page */
$this->denyAccess();
 
}
 
}
 
/**
 * Deny Access Function
 * Redirects to errorPage, this can be called from an action using the action helper
 *
 * @return void
 **/
public function denyAccess()
{
   $this->_request->setModuleName($this->_errorPage['module']);
   $this->_request->setControllerName($this->_errorPage['controller']);
   $this->_request->setActionName($this->_errorPage['action']);
}
 
/**
 * initialize the acl object and resources
 * for the roles used in the application
 *
 */
private function _initAcl()
{
   /*
    * define access control list
    */
   $this->_acl = new Zend_Acl();
 
   /**
    * define acl for default role
    */
   $this->_acl->addRole(new Zend_Acl_Role('defaultRole'))
        ->add(new Zend_Acl_Resource('index'))
        ->add(new Zend_Acl_Resource('portfolio'))
        ->add(new Zend_Acl_Resource('user'))
        ->allow('defaultRole');
 
   /**
    * define acl for administrator
    */
   $this->_acl->addRole(new Zend_Acl_Role('admin'))
        ->add(new Zend_Acl_Resource('admin:index'))
        ->add(new Zend_Acl_Resource('admin:cpanel'))
        ->add(new Zend_Acl_Resource('admin:user'))
        ->add(new Zend_Acl_Resource('admin:page'))
        ->addRole(new Zend_Acl_Role('default'))
        ->allow('admin');
 
   }
 
}
 
Init.php
<?php
 
require_once 'Zend/Controller/Plugin/Abstract.php';
class Zend_Controller_Plugin_Init extends Zend_Controller_Plugin_Abstract
{
    public function __construct()
    {
        // require configuration
        require_once 'Zend/Config.php';
 
        // get configuration from ini file
        $config = new Zend_Config_Ini('../application/config.ini', 'dev');
 
        // connect to the database
        $db = new Zend_Db_Adapter_Pdo_Mysql($config->database->params);
 
        // assign the db adapter to be default for our models
        Zend_Db_Table::setDefaultAdapter($db);
 
        // register configuration at the registry
        Zend_Registry::set('config', $config);
 
        Zend_Registry::set('db', $db);
 
        // start layout mvc
        Zend_Layout::startMvc(array(
            'layoutPath' => '../application/layouts',
            'layout' => 'main'
        ));
    }
 
}

6 thoughts on “Zend Framework – quick tutorial (part 3) – front controller plugins

  1. Thanks for the nice article. I am a newbie to Zend Framework. I am trying to add a plugin for ACL. But, I am not sure if it is a good idea to mix your own application code with the library that is shipped with the framework. This will make it difficult to change version. Will it not?

  2. @sk – of course your case might be different and perhaps you’ll need a slight modification, but however the ACL plugin’s basic usage is to give proper permissions for the different roles, so you can try to mix whatever you want from the code I’ve written. If you’ve problems with that, don’t hesitate to write me, I’ll be glad to help!

    best regards,
    stoimen

Leave a Reply

Your email address will not be published. Required fields are marked *