Zend Framework Acl with example

5 Nov

Zend_Acl provide implementations for privileges management using roles and resources.
Resources
It is an object to which access is controlled.
Zend provide very simple way to create a resource. Simply implement Zend_Acl_Resource_Interface that provide single method getResourceId().You must override this method in your class.
You can add multiple resources to Zend_Acl. These resource will be added as tree structure. Treee structure allow you to organize resources from general to the specific.
The resource on the top of tree structure will have general privileges, while nodes down in the tree structure will have more specific privileges.
Roles
Role is an object that request access to a resource.
Creation of role is also simple in Zend_Acl. Implement Zend_Acl_Role_Interface and override it getRoleId() method. This is the only method Zend_Acl_Role provided.
In Zend_Acl, Role can be inherited form one or more roles.
To create resources and roles, you will need to first create Zend_Acl instance as

$acl = new Zend_Acl();

And then add role and resources to it as follows

$acl->add(new Zend_Acl_Resource(‘view’));
$acl->add(new Zend_Acl_Resource(‘edit’));
$acl->add(new Zend_Acl_Resource(‘delete’));

Once we create roles and resources we can assign different privileges to different roles on different resources as

$acl->allow(‘guest’,null,’view’);
$acl->allow(‘editor’,array(‘view’,’edit’));
$acl->allow(‘admin’);

Similarly we can use deny() method of Zend_Acl for access denials as

$acl->deny(‘guest’,null,array(’edit’,’delete’));

Later in our code we can check privileges as

$acl->isAllowed(‘guest’,null,’view’);

isAllowed() method return boolean value either true or false based on the privileges.
To see how can we use Zend_Acl component in our applications lets take a simple example.
Let we have different controllers, e.g news, latestNews, Announcements with each having the following actions

<?php
class NewsController extends Zend_Controller_Acion
{
public function viewAction()
{
// add your view code.
}

public function editAction()
{
// add your edit code.

}
public function deleteAction()
{
// add your edit code.

}
}
?>

Similarly create other controllers as well.
Let we have the following specifications

  • “guest” can access only view contents, so he can access only “view” action
  • “editor” can access view and edit action, but cannot delete.
  • “admin” have all the privileges, so he can access all the actions.

To set our roles we will need to create following directory structure
library/My/Controller/Helper/
And
library/My/Controller/Plugin/
In your helper directory create Acl.php and place the following code in it.

<?php
class My_Controller_Helper_Acl
{
public $acl;
public function __construct()
{
$this->acl = new Zend_Acl();
}
public function setRoles()
{
$this->acl->addRole(new Zend_Acl_Role(‘guest’));
$this->acl->addRole(new Zend_Acl_Role(‘editor’));
$this->acl->addRole(new Zend_Acl_Role(‘admin’));

}

public function setResources()
{

$this->acl->add(new Zend_Acl_Resource(‘view’));
$this->acl->add(new Zend_Acl_Resource(‘edit’));
$this->acl->add(new Zend_Acl_Resource(‘delete’));

}

public function setPrivilages()
{
$this->acl->allow(‘guest’,null,’view’);
$this->acl->allow(‘editor’,array(‘view’,’edit’));
$this->acl->allow(‘admin’);
}
public function setAcl()
{
Zend_Registry::set(‘acl’,$this->acl);
}
}
?>

In the code above we are defining our class. In constructor we instantiate Zend_Acl. Then we define three public methods

  • setRoles(): add Roles to the acl object.
  • setPrivilages(): set different privileges to different roles.
  • setAcl() : store acl object using Zend_Registry for future use. This is compulsory.

Now in Library/My/Controller/Plugin/, create Acl.php and place the following code.

class My_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$acl = Zend_Registry::get(‘acl’);
$usersNs = new Zend_Session_NameSpace(“members”);
If($usersNs->userType==’’){
$roleName=’guest’;
} else {
$roleName=$userType;
}

$privilageName=$request->getActionName();
if(!$acl->isAllowed($roleName,null,$privilageName)){
$request->setControllerName(‘Error’);
$request->setActionName(‘index’);
}
}
}
?>

Explanation:
In the code above we are creating plugin by extending it form Zend_Controller_Plugin_Abstract and override preDispatch() method.
In preDispatch() method we get reference to $acl object using Zend_Registry. This object was store in the registry earlier.
Next we instantiate Session Namespace and check userType. If this is first attempt to access our application we give user a role “guest”. We can set this type at our authentication and give user a specific type when he login.
Next we get Action name by using $request->getActionName() and assign it to $privilageName.
The next line are very crucial. We check the privileges
if(!$acl->isAllowed($roleName,null,$privilageName))
if the above condition is true. It means that the user hasn’t had the privileges to access the requested Action.
So we redirect user to ErrorController’s Index action.
If the condition is false then he access the particular action.
We have now nearly done. However you will need to add the following code to your bootstrap file.

$helper= new My_Controller_Helper_Acl();
$helper->setRoles();
$helper->setResources();
$helper->setPrivilages();
$helper->setAcl();

And then

$frontController->registerPlugin(new My_Controller_Plugin_Acl());

That it your simple role management application.
Now if you first request
http://yourhost/news/view
it will give you access to the specified view Action of the news or any other controller.
However if you request
http://yourhost/news/edit/
you will be redirected to the Error Controller’s index action. I haven’t mention Error Controller, so you better create your own.
For further queries post your comments.

12 Responses to “Zend Framework Acl with example”

  1. xprt64 November 8, 2008 at 1:08 pm #

    A very simple and a very good start example for those interested in implementing access control in their applications.
    For me it was useful.

  2. Vaidas December 18, 2008 at 3:19 pm #

    Everything looks simple, the only thing that I didn’t understand is how I assign user to different roles… How does the ACL know who is loged in …. guest, admin or editor

  3. Faheem Abbas December 19, 2008 at 9:00 am #

    When user login, simply write- write this code where you have placed code for the login purpose.
    $usersNs = new Zend_Session_NameSpace(“members”);
    $usersNs->userType = ‘admin/editor/publisher’;

  4. Software Developer July 20, 2009 at 4:31 pm #

    Do you really think a Helper is the right place to manage the ACL stuff?
    Sounds a bit strange to me, but i didn´t read that much about the Helper concept, i just know the view helpers.

  5. Erick Martinez October 5, 2009 at 10:43 pm #

    I actually think there’s no need to create an action helper since you are instantiating the helper on the bootstrap, not on the action itself, in fact all the action seems to take place on the action plugin, I mean, you could even define the acl rules just in it.

    I believe the purpose of having an action helper would be to directly deal with the request, response using predispatch method in a similar way you use it on the action plugin. Though I think this would be useful only if you would like to perform this validation just over some of the actions.

    Please let me know if I am missing something since I am just redefining my access control and any suggestions are accepted!

  6. phpzend November 3, 2009 at 7:49 am #

    nice site!, instead of error page, I would go to the login page, for example:

    if(!$acl->isAllowed($roleName,null,$privilageName)){
    $urlOptions = array(‘controller’ => ‘error’,
    ‘action’ => ‘login’
    );
    $redirector = new Zend_Controller_Action_Helper_Redirector();
    $redirector->gotoRouteAndExit($urlOptions, null, true);
    }

  7. AgeValed November 14, 2009 at 5:38 am #

    how can i change the user type?¡¡

  8. John Eway December 11, 2010 at 4:46 pm #

    Zend_Acl is combined with Zend_Auth and Zend_Navigation for maximum efficiency.

Trackbacks/Pingbacks

  1. ACL in MVC? - Zend Framework Forum - January 7, 2009

    […] and permissions in the same place? you can do it all in one place, or not.. your choice btw: Zend Framework Acl with example Zend Framework & Zend_Acl / Zend_Auth Example […]

  2. php,php freelance, php developers » Zend Acl - how to - April 2, 2009

    […] of my readings from the site below https://zendguru.wordpress.com/2008/11/05/zend-framework-acl-with-example/ […]

  3. Zend tutorial - February 13, 2011

    […] Google is your friend. Example: "Zend Framework ACL Tutorial" gives the following: Zend Framework Acl with example ? Zend Framework Hope this gives you a few ideas of where to start looking for help! I haven't read the full book, […]

  4. Useful Zend Framework Resources for Developers, « Tournas Dimitrios - April 9, 2011

    […] Zend Framework ACL With Example: When talking about Auth, how can one ignore the need for ACL? Today’s web application demand a fully functional and feature rich ACL library, and Zend comes with one. But once again, Zend’s manual is just too technical. This beautiful blog post explains how to use the Zend ACL, along with a much needed example. Again, a useful read if you want to learn the coding structure of Zend Framework. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: