Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : ControllerPluginManager – Append Custom Controller Plugin to All Controller

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on August 23, 2012

In most of applications, you often need to set something that happen in all whole application. It can be global authorization like your ACL depend on the module/controller/action that accessed. In this post, I will show you the trick.

Firstly, you need a component \Zend\Mvc\MvcEvent that passed to your ControllerPlugin.

//filename : module/ZfCommons/Module.php;
namespace ZfCommons;

use Zend\Mvc\MvcEvent,

class Module implements
    public function onBootstrap(MvcEvent $e)
        $eventManager        = $e->getApplication()->getEventManager();
        $eventManager->attach('route', array($this, 'loadConfiguration'), 2);
        //you can attach other function need here...

    public function loadConfiguration(MvcEvent $e)
        $application   = $e->getApplication();
	$sm            = $application->getServiceManager();
	$sharedManager = $application->getEventManager()->getSharedManager();
        $router = $sm->get('router');
	$request = $sm->get('request');
	$matchedRoute = $router->match($request);
	if (null !== $matchedRoute) { 
                function($e) use ($sm) {
                      ->doAuthorization($e); //pass to the plugin...    
    public function getAutoloaderConfig(){ /*common code */}
    public function getConfig(){ /* common code */ }

So, you can create your plugin that retrieve the MvcEvent :

//filename : module/ZfCommons/src/ZfCommons/Controller/Plugin/MyPlugin.php
namespace ZfCommons\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin,
    Zend\Session\Container as SessionContainer,
    Zend\Permissions\Acl\Role\GenericRole as Role,
    Zend\Permissions\Acl\Resource\GenericResource as Resource;
class Myplugin extends AbstractPlugin
    protected $sesscontainer ;

    private function getSessContainer()
        if (!$this->sesscontainer) {
            $this->sesscontainer = new SessionContainer('zftutorial');
        return $this->sesscontainer;
    public function doAuthorization($e)
        //setting ACL...
        $acl = new Acl();
        //add role ..
        $acl->addRole(new Role('anonymous'));
        $acl->addRole(new Role('user'),  'anonymous');
        $acl->addRole(new Role('admin'), 'user');
        $acl->addResource(new Resource('Application'));
        $acl->addResource(new Resource('Login'));
        $acl->deny('anonymous', 'Application', 'view');
        $acl->allow('anonymous', 'Login', 'view');
        //admin is child of user, can publish, edit, and view too !
            array('publish', 'edit')
        $controller = $e->getTarget();
        $controllerClass = get_class($controller);
        $namespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
        $role = (! $this->getSessContainer()->role ) ? 'anonymous' : $this->getSessContainer()->role;
        if ( ! $acl->isAllowed($role, $namespace, 'view')){
            $router = $e->getRouter();
            $url    = $router->assemble(array(), array('name' => 'Login/auth'));
            $response = $e->getResponse();
            //redirect to login route...
            /* change with header('location: '.$url); if code below not working */
            $response->getHeaders()->addHeaderLine('Location', $url);

Last step, register the plugin into your module config :

//filename : module/ZfCommons/config/module.config.php
'controller_plugins' => array(
    'invokables' => array(
       'Myplugin' => 'ZfCommons\Controller\Plugin\Myplugin',

Done 😉
Why you need to create a controller plugin ? can We set a logic in Module Class ? Yes. We can, but Module Class is not the place you create a large logic. It’s place you register serviceManager or assets.

References :
1. http://lab.empirio.no/custom-controller-plugin-in-zf2.html
2. http://zf2.readthedocs.org/en/latest/modules/zend.mvc.plugins.html
3. https://github.com/EvanDotPro/EdpModuleLayouts/blob/master/Module.php

107 Responses

Subscribe to comments with RSS.

  1. thomas said, on September 6, 2012 at 10:49 pm

    I think with the release canidate from zend 2.0 you need to define a priority for the event. A number larger then 2 or it will be called after the method has been executed.

    $eventManager->attach(‘dispatch’, array($this, ‘loadConfiguration’), 2);

  2. thomas said, on September 6, 2012 at 10:50 pm

    *after the Controller-action-method

  3. samsonasik said, on September 7, 2012 at 12:44 pm

    Thanks, I just updated to ZF 2.0.2. It’s fixed now.

  4. Mat said, on September 25, 2012 at 2:06 am

    This post was very helpful for me. I was trying to figure out how to get code into the dispatch event for a particular controller so I can check for authentication. This guide worked great for me. Thanks!

  5. samsonasik said, on September 25, 2012 at 11:02 am

    You’re welcome 🙂

  6. Bill H said, on September 29, 2012 at 11:27 pm

    This was exactly what I needed, thank you!

  7. Paladyn said, on October 25, 2012 at 7:45 pm

    Great tutorials you have here!
    Still I have some little question for you:
    How to add table service to controller plugin? I want to build dynamic acl from db (I store there roles and roles privileges).

  8. samsonasik said, on October 25, 2012 at 11:04 pm

    Yes, you can, you can call dbAdapter from controller plugin by call


    or other service, you can call as easy as that.

    • Paladyn said, on October 26, 2012 at 9:22 pm

      Thanks! getController is method I was looking for.

  9. Paladyn said, on October 28, 2012 at 12:30 am

    I have one more problem. I`m trying to build view helper to set up menu according to acl table. I`m trying to get acl, which was set in plugin but somehow acl object is empty. I feel so dump in ZF2, most of my ZF1 standards are gone here (this is very good for sure).

    • samsonasik said, on October 28, 2012 at 1:17 pm

      to show menu, loop from table, check isAllowed from Acl that already register role, resource and right.

      • Paladyn said, on October 30, 2012 at 5:34 pm

        Problem is that I somehow can`t get registered roles/resources in view helper. Probably I`m trying to get this values wrong. This values are registered for sure, because I can see this in session.

      • samsonasik said, on October 30, 2012 at 8:06 pm

        you save session role in the session. but for resource, save in session it’s not good idea. you can create a class to handle register of resources, and called by Service locator.

      • Paladyn said, on October 30, 2012 at 8:29 pm

        Should`t I be able to get this values just from acl object which was set in Plugin? When I try to check isAllowed(), I`ve got error that role is`t set yet. Is controller plugin launched after view helpers? I`ve got user important info in ‘user’ (like name, acl_role) session and getting this values is`t a problem. I have problems to access values stored in acl object inside view helper.

      • samsonasik said, on October 30, 2012 at 9:09 pm

        ‘save’ acl you’ve configure into ServiceManager, and get it from anywhere.

      • Paladyn said, on October 30, 2012 at 9:58 pm

        Thanks again mate! For some dump way I thought plugin is returning acl object…

      • samsonasik said, on October 30, 2012 at 11:21 pm

        You’re welcome 🙂

  10. houssemzaier said, on October 28, 2012 at 2:59 am

    Hi my friend this tutorial helps me very well to integrate Doctrine 2.3 in ZF 2.0.3 it’s really new and works 100%
    I just want to share knowledge between us 🙂 http://www.youtube.com/watch?v=8NE-sYRQMOY
    Now after I’ve got Doctrine I have to know how to master the using of this ORM.
    Please if you have some advice and any ebook or some tutorial please tell me about it because I’m really a newbie .
    By the way should I go back to ZF1 to master this ORM.??
    Is it really better to use ZF_table to control data than using doctrine2 ?
    I hope I can find answers from you samsonasik and thank you very much !!!! 🙂

    • samsonasik said, on October 28, 2012 at 1:29 pm

      i’m not fan with full-blown ORM. Just my perspective, ZF2 zend\db is enough. You can still manage table relationship with Zend\Db.

      but i suggest this blog http://www.michaelgallego.fr/blog/ for learn with doctrine more deeply.

      • houssemzaier said, on October 28, 2012 at 5:38 pm

        Thank you for your precious help and for the rapid feedback.
        All this blog is a tresor for ZF developer I ‘ve already share it with my friends 🙂
        Mr Samsonasik:
        You know that ORMs make life easier with handling Entitys and OO aspect (methodes…are of course easier than SQL queries)
        for example I have some experience in asp.net programming I use to work on code first approche . I create Entity than of course my Entity Framework witch is an ORM generate my Tables.
        Can we use zend\db to generate my databases ? or should I create tables than manage the table relationship with Zend\Db.?

        I hope I can find the answer , your advises are so interesting for me Sir. Peace

      • samsonasik said, on October 28, 2012 at 8:49 pm

        in zf1, generate table and model can be utilized by zend_tool.I hope Zf2 ‘tool generator’ will come to us in version 2.1, or next version, and give us more than that.

        in my perspective, i will use all functionality in zf component first rather than use another 3rd party library ( i’m using doctrine annotation for build a form, but i know build form using zend\form ‘manually’ ). i still learning process in understanding zend\db, so i will give my time to learn it first, rather than using another 3rd party library. or, i will create my own module to generate table/model for easy-ing my process in developing application.

        if you want to learn doctrine, it’s good. if it can make your process in building application, just use it. it just a choice, melon or apple :). the most important is the concept behind it, place logic in the model, place ‘traffic’ of req/response in controller, and view, is just for view. if in view must be a logic, it’s must be a logic to ‘process’ the view, not process the data.

  11. houssemzaier said, on October 28, 2012 at 10:31 pm

    I got big respect for ya ! wish I know you better and I hope all success for you .Peace 🙂

  12. TomAtom said, on November 15, 2012 at 5:22 am

    Thanks for example, helps me. Why is controller action executed before redirectinng to login? In ZF1 was preDispatch plugin executed before controller action. How can i do this?

    • samsonasik said, on November 15, 2012 at 12:21 pm

      You can set the priority to <0 to EventManager for less priority.

      • TomAtom said, on November 16, 2012 at 1:39 am

        thank you. if i set prioity <2 (1,0,-1,-2,-200) controller plugin is not executed :-(.

      • samsonasik said, on November 16, 2012 at 2:50 am

        with less priority, the plugin excecuted lately. maybe break because of the lately. we need to detect the resource first ( namespace, controller, action) to specify the permissions of the roles.

    • Rhabarber said, on December 5, 2012 at 6:51 pm

      Did you find a solution? I have the same problem.
      The redirection works fine but my controller action gets executed (which i do not want).

      • samsonasik said, on December 5, 2012 at 11:58 pm

        for checking, try to not attach into eventmanager. code that in onbootstrap.

      • TomAtom said, on December 6, 2012 at 1:58 am

        solution of this problem. it works for me. redirection is executed before action execution.

        public function onBootstrap(\Zend\Mvc\MvcEvent $e) {
        $application = $e->getApplication();
        $sm = $application->getServiceManager();
        $eventManager = $application->getEventManager();
        function($e) use ($sm) {

        And one new line after redirection..
        $response->getHeaders()->addHeaderLine(‘Location’, $url);

      • samsonasik said, on December 6, 2012 at 2:21 am

        great !

      • Rhabarber said, on December 6, 2012 at 3:11 pm

        Thanks! Works great 🙂

  13. Rickard said, on November 18, 2012 at 8:00 pm

    Hi, could you please add what files what goes in to? 🙂

  14. samsonasik said, on November 18, 2012 at 8:24 pm

    You can grab from my github account : https://github.com/samsonasik/SanCommons

  15. piasek said, on January 3, 2013 at 12:46 am

    Hi I got small problem, i try use your code and in module.config I change name to:

    “‘controller_plugins’ => array(
    ‘invokables’ => array(
    ‘Task\Controller\Acl’ => ‘Task\Controller\Plugin\Aclplugin’, // ‘Myplugin’ => ‘ZfCommons\Controller\Plugin\Myplugin’,


    and in Module.php

    public function loadConfiguration(MvcEvent $e)
    $application = $e->getApplication();
    $sm = $application->getServiceManager();
    $sharedManager = $application->getEventManager()->getSharedManager();

    function($e) use ($sm)
    ->get(‘Task\Controller\Acl’) //->get(‘Myplugin’)
    ->doAuthorization($e); //pass to the plugin…


    So as you notice I have changed only ‘name’ at config.module for controller/invokables

    and i got error:
    Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Task\Controller\Acl

    any idea why? or how i can find out what is wrong?

    I’m new in Zend Framework

    • samsonasik said, on January 3, 2013 at 2:06 am

      controller_plugins and view_helpers should able to called by controllers and view via

      $plugin = $this->MyFirstPlugin();

      so, i think the FQCN name for controller_plugins and view_helpers in this case is NOT allowed ( at least until ZF2 version 2.0.6 ).

      • piasek said, on January 3, 2013 at 3:47 am

        By FQCN you mean ‘Task\Controller\Acl’?
        first i use as you in your example as well ‘Myplugin’ name and i got the same error…

      • samsonasik said, on January 4, 2013 at 2:35 pm

        Yes. if you’re namespace-ing in your module is right, it should be worked 🙂

  16. Optimus said, on January 4, 2013 at 10:44 pm

    Hi, I cloned this module in my ZF2 ver 2.0.6 (Skeleton App) and got error as soon as I enabled it. It was working fine with 2.0.4

    "Fatal error: Uncaught exception 'Zend\ModuleManager\Listener\Exception\InvalidArgumentException' with message 'Config being merged must be an array, implement the \Traversable interface, or be an instance of Zend\Config\Config. NULL given.' in D:\htdocs\ZF2\zf206\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php:325 Stack trace: #0 D:\htdocs\ZF2\zf206\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php(135): Zend\ModuleManager\Listener\ConfigListener->addConfig('SanCommons', NULL) #1 [internal function]: Zend\ModuleManager\Listener\ConfigListener->onLoadModule(Object(Zend\ModuleManager\ModuleEvent)) #2 D:\htdocs\ZF2\zf206\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(464): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent)) #3 D:\htdocs\ZF2\zf206\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(208): Zend\EventManager\EventManager->triggerListeners('loadModule', Object(Zend\M in D:\htdocs\ZF2\zf206\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php on line 325"

    Any Idea?

    • samsonasik said, on January 5, 2013 at 6:02 am

      based on your error, please take look module.config.php in module/SanCommons/config. it look like your module.config.php is NULL, change with return array();

      • Optimus said, on January 5, 2013 at 9:59 am

        Its already returning an array in SanCommons/config/module.config.php

        'invokables' => array(
        'Myplugin' => 'SanCommons\Controller\Plugin\Myplugin',

        Btwn, I am getting this error only if I clone the entire module (SanCommons) from git. It’s still working fine if I manually create acl plugin into some another module (like application). Just wondering why happening so…

      • samsonasik said, on January 5, 2013 at 2:02 pm

        Ok, thanks. I will take a look on this 🙂

  17. Ankit Shah said, on January 7, 2013 at 6:39 pm


    For file, “module.php” located at “SanCommons-master/Module.php” have two functions as follows,

    public function getAutoloaderConfig(){ /*common code */}
    public function getConfig(){ /* common code */ }

    Replace that with common code of

    public function getAutoloaderConfig()
    return array(
    ‘Zend\Loader\ClassMapAutoloader’ => array(
    __DIR__ . ‘/autoload_classmap.php’,
    ‘Zend\Loader\StandardAutoloader’ => array(
    ‘namespaces’ => array(
    __NAMESPACE__ => __DIR__ . ‘/src/’ . __NAMESPACE__,

    public function getConfig()
    return include __DIR__ . ‘/config/module.config.php’;

    That’s it.

    • OptimusCrew said, on January 7, 2013 at 8:26 pm

      Thanks 🙂

  18. Mircea Ranetti said, on January 8, 2013 at 6:41 pm


    I have a question about this post. You’re using the Event\Manager::getTarget() and u use your namespace as a resource in ACL. I found that the getTarget() method returns the controller object only if the action method is executed. If you set a higher priority in the attach() method, the controller won’t be initialized and the getTarget() method will return a Mvc Application Object.

    What i’m trying to say is that regarding your way of handling the acl, the action method would be executed before the acl checks the permission.

    From my point of view this Access Control is useless. Am i wrong?

    Waiting for your reply,
    Thanks in advance.


    • samsonasik said, on January 9, 2013 at 1:46 am

      Hello… Mircea..
      My post has been updated. I add a priority to shared events. It should be works if you want to get controller from getTarget() before action method executed.

      No. getTarget() return controler. I’m attach into Zend\Mvc\Controller\AbstractActionController, not Zend\Mvc\Application, so it return controller.

      • Mircea Ranetti said, on January 9, 2013 at 2:15 am

        I’ve tested it with the priority order added on the event binding before your reply. Try to put a die() in your action method in the called controller (i’m not talking about the pluginController). If the priority is to high, the controller is not initialized, and therefore, the getTarget Will return the Zend\Mvc\Application service instead the currentController.
        I think you need to change the way your doing the ACL because this is a major security leak. The application is processing the request on the dispatch event executine the action, and after that is checking the permissions.. wich is not ok.

        Please test this and correct me if i’m wrong.
        Best regards.


      • samsonasik said, on January 9, 2013 at 2:30 am

        can you give me a better way, maybe via ModuleManager ?

      • Mircea Ranetti said, on January 9, 2013 at 2:43 am

        First of all the purpose of my comment is not for me to give you a better way…. is to warn you that you are not accomplishing the main purpose of this component, that you have a MAJOR security leak and you have mislead some people with this!

        So there isn’t a better way because this code is useless.
        Sorry to tell you that.

  19. Mircea Ranetti said, on January 9, 2013 at 2:55 am

    If you want to make it work, my opinion is first of all to bind your “loadConfiguration” method to the MvcEvent :: EVENT_ROUTE. This will ensure you that this is done before initializing the controller.

    After that you need to get the requested resource in order to check this with your ACL library. So you are doing that with the controller namespace. But now you need to find another way. The best way is through the match() method in the router service. This will be something like:

    $serviceManager = $event->getServiceLocator();
    $router = $serviceManager->get(‘router’);
    $request = $serviceManager->get(‘request’);

    $matchedRoute = $router->match($request);

    if (null !== $matchedRoute) {
    $controller = $matchedRoute->getParam(‘controller’);

    This method requires a better routing management and a bit different perspective for loading and managing your resources, but it should work.

    Best regards.

    Mircea Ranetti

    • samsonasik said, on January 9, 2013 at 3:31 am

      fix typo, i think

      $serviceManager = $event->getServiceLocator(); 

      should be

      $serviceManager = $event->getApplication()->getServiceManager();

      I just tested your solution in “real” application, and it just make a mess with hight/low priority. The resources is not registered.

      For now, i can’t say it is the right way, but i can say it just worked.

      • Mircea Ranetti said, on January 9, 2013 at 3:40 am

        For shure, i’m not a master in the chaining methods for ZF2. If you use the “route” event instead of “dispatch”, you don’t even need to use priority in the attach method. And as i said.. you need another way to handle resources.

        I repeat, your way has a security leak. Try to acces a controller/action that deletes something and you don’t have permisssions. You’ll see that you will be redirected… but the item will also be deleted

      • samsonasik said, on January 9, 2013 at 4:08 am

        Oops, You’re right. I’ve changed ‘dispatch’ with ‘route’ in eventmanager. I have been updated my post, but for attaching plugin controller, it still need dispatch event. and in the last after redirect, I add the following code :


        Thank You very much….

      • Mircea Ranetti said, on January 9, 2013 at 5:05 am

        The purpose of plugin controllers it’s not the same like in ZF1. If you want to use this for your business logic it’s ok. You can attach this to any event, because your not using this through the controllerplugin service.
        $e->stopPropagation() does not prevent from executing the requested action before the acl if the priority is higher. Try this and you’ll see i’m right.

        Again.. i prevent you and others that are using this code that the purpose of the ACL is not reached! The actions are executed without permissions, even though the redirect is done afterward.

      • samsonasik said, on January 9, 2013 at 5:36 am

        I’ve tried die(‘test’) in actions, and set priority to 2000000 and the actions is not executed because of $e->stopPropagation()

      • Mircea Ranetti said, on January 9, 2013 at 6:13 am

        You’re right! StopPropagation() does the work!

  20. Moazzam said, on January 14, 2013 at 12:49 am

    Great tutorial! I have been wrecking my brains trying to figure out how ACL is done in ZF2

  21. Josias Duarte said, on January 26, 2013 at 3:09 am

    I have a question, I don’t know if I use ACL or RBAC. In my project I’ll not use roles, the permissions/privileges will be mapped directly with every user, it will be stored in the database, and I’ll have tables like this:
    | Id | Name | Password |
    |1 | Josias | 12345 |
    | 2 | Abdul | 54321 |

    | Id | Key |
    | 1 | View.Product |
    | 2 | Add.Product |
    | 3 | Edit.Product |
    | 4 | Delete.Product |

    | User_Id | Permission_Id |
    | 1 | 1 | // Josias can view products
    | 1 | 2 | // Josias can add products
    | 1 | 3 | // Josias can edit products
    | 1 | 4 | // Josias can delete products
    | 2 | 1 | // Abdul can view products

    Since the user have a many-to-many relationship with the permission, the permission settings is very flexible, the problem is that I don’t know if I use ACL or RBAC. What do you think it’s better for this purpose?

    • samsonasik said, on January 26, 2013 at 5:12 pm

      distinguish user and role, i think you need to add create role table to do that 🙂

      • Josias Duarte said, on January 26, 2013 at 8:11 pm

        Role is a set of permissions, and I don’t want that because I want to be able to change each permission individually for each user. E.g. If I have a role, and add one more permission to this role, every user that is linked to this role will have this permission. What I want to be able to add/delete permission to each user individually, that’s why I don’t want a ‘Role’ table.

        I don’t know if this is a good explanation… 🙂

        One more thing, do you know when zf2 2.1.0 will be released? Will Zend\Permission\Rbac be included?

        Thanks for everything man, your blog rocks!

      • samsonasik said, on January 27, 2013 at 12:19 am

        ok, but it’s not the concept of ACL.
        Rbac will be in ZF 2.1.0. based on mailing list, In 2nd week of February 🙂

  22. Josias Duarte said, on January 27, 2013 at 1:52 am

    ok, thank you anyway!

    waiting for the new version. 😀

  23. Gulzar said, on January 29, 2013 at 8:47 pm

    Thx Sam, This was a great help what i want to know is that how to make This ACL apply on some Specific action?

  24. Michal Malinowski said, on July 3, 2013 at 6:38 pm

    Hi. Regarding to above questions and problems. I had same problem as “piasek said, on January 3, 2013 at 12:46 am” and i finally sove it. You have to insert your Plugin in module.php not module.config.php. So after that your module.php should conatin this:

    public function onBootstrap(MvcEvent $e)
    $application = $e->getApplication();
    $sm = $application->getServiceManager();
    $eventManager = $application->getEventManager();
    $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, function($e) use ($sm) {

    public function getServiceConfig()
    return array(
    ‘invokables’ => array(
    ‘Myplugin’ => ‘Cms\Controller\Myplugin’,

    Of course rest of functions in module.php should be like before applying plugin and instead of Cms should be your module Namespace.

    Kind Regards

    • samsonasik said, on July 4, 2013 at 2:33 am

      great! but you should put the authorization on route event, not dispatch 😉

      • Michal Malinowski said, on July 4, 2013 at 2:42 pm

        Yes i will do that today becouse on dispatch every time controller is Zend from MvcEvent 🙂 On route i should get every time current Controller. BTW great tutorial, the best one about Acl in the internet so far.

  25. Michal Malinowski said, on July 4, 2013 at 2:56 pm

    Sorry for another comment 😀 I cant edit my reply. Regarding to above. I still get only “Zend\Mvc\Application” as Contoller on every page. And on every page its the same. I have few controllers on my test website but this plugin dont get its name after substr ofc i have Zend resource all the time.

    Any idea how to get for example IndexController instead of Zend\Mvc\Application ?

    Best Regards

    • Michal Malinowski said, on July 5, 2013 at 5:12 pm

      I solved it out. If you want to get to your Plugin Controller name and Action name you should put inside your public function doAuthorization($e) this code:

      $application = $e->getApplication();
      $sm = $application->getServiceManager();
      $eventManager = $application->getEventManager();
      $router = $sm->get(‘router’);
      $request = $sm->get(‘request’);
      $matchedRoute = $router->match($request);
      if (null !== $matchedRoute) {
      $controllerName = $matchedRoute->getParam(‘controller’);
      $controllerName = substr($controllerName, 0, strpos($controllerName, ‘\\’));
      $actionName = $matchedRoute->getParam(‘action’);
      echo “Route not found”;

      Then $controllerName will be your actual Controller Name and ActionName will be your actual Action Name 🙂
      It is ofc possible to make this code less weight using function on initialize +class variables and return.

      If you have any idea guys how to use this solution inside Module.php in the way to send ControllerName and ActionName variables to doAuthorization function it will be verry helpfull and will make this code less weight. Then you dont have use those getApllication etc. commands second time (it is used once in Module.php and second time in doAuthorization function inside Myplugin.php… it have to be another way but I didnt find it so far.

      Best Regards !

  26. Vimal raj.S said, on July 10, 2013 at 1:16 pm

    Dear asik, your blogs are helping me to survive in zend frame work 2, now i need you r help

    Kindly tell me In ZF2 where i have to declare common arrays (Countries , cities , pincode , etc … )

    in autoload/local.php ? or autoload/global.php ? or autoload/commonarrays.global.php ?

    and i need to access those arrays from Model class and Controller class.

    • samsonasik said, on July 10, 2013 at 11:07 pm


      • Vimal raj said, on July 10, 2013 at 11:27 pm

        Yes it works in controller class, but i need to access that common arrays in


        to show a select box for ‘countries’ . I cant create instance of servicemanager in ‘SignupForm.php’.

        What i have to do?, please tell me i am checking my mail for every five minutes to see your answer

      • samsonasik said, on July 10, 2013 at 11:40 pm

        your form should implements ServiceLocatorAwareInterface , for example :

        namespace YourModule\Form;
        use Zend\Form\Form;
        use \Zend\ServiceManager\ServiceLocatorAwareInterface;
        use \Zend\ServiceManager\ServiceLocatorInterface;
        class YourForm extends Form implements ServiceLocatorAwareInterface
             protected $serviceLocator;
             public  function __construct()
           //CHECK HERE...
                        'name' => 'email',
                        'type' => 'Email',
                        'attributes' => array(
                            'id' => 'email'
                        'options' => array(
                            'label' => 'Email:'
            public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
                $this->serviceLocator = $serviceLocator;
            public function getServiceLocator()
                return $this->serviceLocator;

        and you can call the form at controller for example that already bring config from file configuration :

         $form = $this->getServiceLocator()->get('FormElementManager')->get('YourModule\Form\YourForm');
  27. Vimal raj said, on July 11, 2013 at 2:10 am

    Sorry for another comment 😀 I cant edit my reply. Regarding to above.

    Fatal error: Call to a member function getServiceLocator() on a non-object in E:\xampp\htdocs\MyProjectName\ZendSkeletonApplication\module\Member\src\Member\Form\SignupForm.php on line 24



    $this->setAttribute(‘method’, ‘post’);
    $this->setAttribute(‘id’, ‘signupform’);
    ‘name’ => ‘firstname’,
    ‘type’ => ‘Text’,
    ‘options’ => array(
    ‘label’ => ‘First Name’,
    ‘name’ => ‘lastname’,
    ‘type’ => ‘Text’,
    ‘options’ => array(
    ‘label’ => ‘Last Name’,
    ‘name’ => ‘username’,
    ‘type’ => ‘Text’,
    ‘options’ => array(
    ‘label’ => ‘User Name’,
    ‘name’ => ’email’,
    ‘type’ => ‘text’,
    ‘options’ => array(
    ‘label’ => ’email’,
    ‘name’ => ‘birthday’,
    ‘type’ => ‘date’,
    ‘options’ => array(
    ‘label’ => ‘DOB’,
    ‘name’ => ‘passwd’,
    ‘type’ => ‘Password’,
    ‘options’ => array(
    ‘label’ => ‘Password’,
    $captcha = new Captcha(‘captcha’);
    $captcha->setOptions(array(‘label’ => ‘Please verify you are human.’));

    ‘name’ => ‘submit’,
    ‘type’ => ‘Submit’,
    ‘attributes’ => array(
    ‘value’ => ‘Go’,
    ‘id’ => ‘SignupSubmitbtn’,

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    $this->serviceLocator = $serviceLocator;

    public function getServiceLocator()
    return $this->serviceLocator;


    • samsonasik said, on July 11, 2013 at 2:21 am

      have you call your form using formelementmanager ?

       $form = $this->getServiceLocator()->get('FormElementManager')->get('YourModule\Form\YourForm');

      if no, you must !, if still failed, try to create a factory for it.

      namespace YourModule\Factory\Form;
      use Zend\ServiceManager\FactoryInterface;
      use Zend\ServiceManager\ServiceLocatorInterface;
      use YourModule\Form\YourForm;
      class YourFormFactory implements FactoryInterface
          public function createService(ServiceLocatorInterface $serviceLocator)
              $form = new YourForm;
              $config = $form->getServiceLocator()->get('Config');
              return $form;

      and register your form to Module::getFormElementConfig()

      class Module
          public function getFormElementConfig()
              return array(
                  'factories' => array(
                      'YourModule\Form\YourForm' =>  'YourModule\Factory\Form\YourFormFactory'

      and then re-try call using FormElementManger

       $form = $this->getServiceLocator()->get('FormElementManager')->get('YourModule\Form\YourForm');
    • Vimal raj said, on July 12, 2013 at 1:40 pm

      Whoa !, I did it , without you i cant , thank you for your timely help……

      I did these:

      In my module.php


      public function getServiceConfig()
      return array(
      ‘factories’ => array(
      // some code goes here //
      // some code goes here //

      /** I added these lines **/
      ‘Member\Form\SignupForm’ => function($sm) {
      $SignupForm = new SignupForm($sm);
      return $SignupForm;
      /** I added these lines **/

      In \module\Member\src\Member\Form\SignupForm.php

      class SignupForm extends Form
      /** I added these lines **/
      protected $serviceManager;

      public function __construct($serviceManager)

      $this->serviceManager = $serviceManager;

      /** I added these lines **/
      // some code goes here //
      // some code goes here //

      In \module\Member\src\Member\Controller\MemberController.php

      $form = $this->getServiceLocator()->get(‘Member\Form\SignupForm’);

      • samsonasik said, on July 12, 2013 at 4:32 pm

        great! but for form instance, you should use getFormElementConfig()

  28. Mark said, on August 2, 2013 at 6:12 pm

    Dear Samsonasik,

    Do you have any idea why this would not work?

    $eventManager->attach(\Zend\I18n\Translator\Translator::EVENT_MISSING_TRANSLATION,function ()
    // do something

    Thanks for this, and your great blog!

  29. Nguyễn Anh Đức said, on November 23, 2013 at 2:38 pm

    You can try name file in the head the code ?. ( I very bad el )

  30. […] suche ich im Netz und suche und komme nicht weiter. Im gleichen Blog sollte es doch das Passende […]

  31. già làng said, on March 4, 2014 at 8:49 am

    Hi samsonasik !
    I always get NULL in $this->getSessContainer()->role. Could you please explain me where you save SessionContainer(‘zftutorial’) before. Thank your tutorial so much !

  32. Skubi Du said, on April 2, 2014 at 4:09 pm

    Greetings! There is something I cant understand. And I’m sure you can make it clear.
    If in the application.config.php I have registered two modules, let say Module1 and Module2, and in Module1 I have 2 controllers..My1Module1Controller and My2Module1Controller and each of the controllers have two actions..index and test. We have the same thing in Module2 (having the same naming convention). How to register the resources in the acl. For example the anonimous role to be able to see only action index from My1Module1Controller and index from My1Module2Controller?

    • samsonasik said, on April 2, 2014 at 10:39 pm

      you need to include the namespace too instead of controller into the acl too then

  33. FraGoTe said, on April 13, 2014 at 11:23 am

    Reblogged this on :: Francis Gonzales ::.

  34. Amit said, on July 18, 2014 at 9:00 pm

    Hello Sir ,

    I need your help .
    I want to set some values from database to layout.phtml .
    right now i am storing values in session which is very bad way.
    i am using many layout file .

  35. FraGoTe said, on March 27, 2015 at 4:36 am

    If I want to obtain the $acl instance in the controller what should I do??

  36. Arón Chávez said, on January 8, 2016 at 5:59 am

    This posts are great and easy to understand, but I’ve a doubt:

    Is It possible to use a plugin for two or more modules?

    Actually I have a little php file that I whant to use, but, if I use the ZF2 controller plugin I have to reply this but this is redundant

    • samsonasik said, on January 8, 2016 at 6:25 am

      plugin = service too. So, it call-able from entire modules in your app.

      • Arón Chávez said, on January 9, 2016 at 9:26 am


        I’ve try to create the plugin controller but i have this error :

        Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for Tools

        #0 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php(103): Zend\ServiceManager\ServiceManager->get(‘Tools’, true)
        #1 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\PluginManager.php(82): Zend\ServiceManager\AbstractPluginManager->get(‘Tools’, Array, true)
        #2 C:\xampp\htdocs\ost-advance\module\Plugins\Module.php(44): Zend\Mvc\Controller\PluginManager->get(‘Tools’)
        #3 [internal function]: Plugins\Module->Plugins\{closure}(Object(Zend\Mvc\MvcEvent))
        #4 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Object(Closure), Object(Zend\Mvc\MvcEvent))
        #5 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners(‘dispatch’, Object(Zend\Mvc\MvcEvent), Object(Closure))
        #6 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php(116): Zend\EventManager\EventManager->trigger(‘dispatch’, Object(Zend\Mvc\MvcEvent), Object(Closure))
        #7 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\Mvc\DispatchListener.php(113): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
        #8 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
        #9 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
        #10 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners(‘dispatch’, Object(Zend\Mvc\MvcEvent), Object(Closure))
        #11 C:\xampp\htdocs\ost-advance\vendor\zendframework\zendframework\library\Zend\Mvc\Application.php(313): Zend\EventManager\EventManager->trigger(‘dispatch’, Object(Zend\Mvc\MvcEvent), Object(Closure))
        #12 C:\xampp\htdocs\ost-advance\public\index.php(17): Zend\Mvc\Application->run()
        #13 {main}

      • samsonasik said, on January 10, 2016 at 12:51 am

        that means the plugin is not registered in ‘controller_plugins’ or not registered via Module::getControllerPluginConfig() or you don’t call via ControllerPluginManager manager, see: http://lab.empirio.no/custom-controller-plugin-in-zf2.html and http://zf2.readthedocs.org/en/latest/tutorials/config.advanced.html?highlight=getcontrollerpluginconfig#configuration-mapping-table , and please do effort

  37. […] utilisé ce plugin pour créer mon […]

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: