Search code examples
zend-frameworkzend-authzend-acl

Zend framework ACL question


I'm new to Zend framework and currently looking at Zend_Acl . There are multiple examples online. In a lot of these example you would see code like this one:

class My_Acl extends Zend_Acl {
  public function __construct() {
    //Add a new role called "guest"
    $this->addRole(new Zend_Acl_Role('guest'));

    //Add a role called user, which inherits from guest
    $this->addRole(new Zend_Acl_Role('user'), 'guest');

    //Add a resource called page
    $this->add(new Zend_Acl_Resource('page'));

    //Add a resource called news, which inherits page
    $this->add(new Zend_Acl_Resource('news'), 'page');

    //Finally, we want to allow guests to view pages
    $this->allow('guest', 'page', 'view');

    //and users can comment news
    $this->allow('user', 'news', 'comment');
  }
}

So basically - we extend our Zend_Acl class where we define roles and resources. I'm sorta failing to understand why would we create separate class versus doing the same thing in for example resource method in the bootstrap and then shoving the result into registry?

Like this for ex:

protected function _initAcl()
{
    $myacl = new Zend_Acl();
    $myacl->addRole(new Zend_Acl_Role('guest'));
    $myacl->addRole(new Zend_Acl_Role('user'), 'guest');
    $myacl->add(new Zend_Acl_Resource('page'));
    $myacl->add(new Zend_Acl_Resource('news'), 'page');
    $myacl->allow('guest', 'page', 'view');
    $myacl->allow('user', 'news', 'comment');

    Zend_Registry::set('acl', $myacl);
}

Am I right in thinking that these ways will give us the same result?

thanks! p.s. damn zend is complicated


Solution

  • Generally speaking, putting this kind of stuff - not just ACL - in its own class provides several benefits, including:

    1. Testability: You now have a single component to which you can apply unit testing.
    2. Extensibility: You can extend it and modify it, if necessary
    3. Portability: Use it in another project simply by dropping it in.

    In this particular case, these might not seem so evident. In a more complex case, these benefits become more apparent. But as with most things, YMMV.

    BTW, I also found - and sometime still do find - learning ZF to be a climb. But I realize that I was learning not just the framework, but also lots of best practices like dependency injection, unit-testing, DRY, SRP, design patterns, etc. I advise you keep at it; it's well worth it. Good luck!