Simple ACL in Zend Framework 2 in 15 minutes

As ZF2 documentation is a little bit confusing I decided to create simple tutorial how to implement ACL in Zend framework 2.

Understanding Zend framework events:

Zend whenever something important is happening in our application triggers a event. As PHP is not multi thread language all logic connected with particular event is being launch at same moment as event was triggered. Example
Function in our class have this code:

And our function in event listener which listens for ‘MySuperEvent’ looks like this:

So when we execute

We should get:
“test test2 test3”

Knowing all of this we can create our first very simple ACL which will only check if controller needs authorization and if user is Signed in.
Firstly we will need to create separeted module called ACL. We can do this with zftool (
vendor/bin/zf.php create module ACL

And after removing unnecessary directories we get file structure like this:

Listening for event

Now when we have created new module we can add our event listener. To do that we need to create it first so we create new file module/Acl/Listener/AclEventListener.php and we put there:

After that we need to register our listener in module/Acl/Module.php so we add to this file:

Important! From now on all controllers needs to implement interface

A bit of explanation

Zend whenever finds controller and action matching our url he triggers MVC event called ‘EVENT_DISPATCH’. We simply listen on this event with our AclEventListener and process it by checkAcl function. Target for this event is our controller so we provide a way to get information if it needs authorization with AclControllerInterface. If controller needs authorization we check if authorization service has identity and if not we redirect user to other url.

And in the end our file structure looks like this:

Apr 6, 2015 | Posted by in Blog, PHP, Zend Framework 2 | 0 comments

Add Your Comment

Your email address will not be published.