code run before every actions in a module ZF2?
Asked Answered
R

1

6

I want to write some code to run before every actions in my module. I have tried hooking onto onBootstrap() but the code run on the other modules too.

Any suggestions for me?

Rosewater answered 13/11, 2012 at 11:57 Comment(0)
A
8

There are two ways to do this.

One way is to create a serice and call it in every controllers dispatch method

Use onDispatch method in controller. 


    class IndexController extends AbstractActionController {


        /**
         * 
         * @param \Zend\Mvc\MvcEvent $e
         * @return type
         */
        public function onDispatch(MvcEvent $e) {

            //Call your service here

            return parent::onDispatch($e);
        }

        public function indexAction() {
            return new ViewModel();
        }

    }

don't forget to include following library on top of your code

use Zend\Mvc\MvcEvent;

Second method is to do this via Module.php using event on dispatch

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module {

    public function onBootstrap(MvcEvent $e) {        
        $sharedEvents = $e->getApplication()->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', array($this, 'addViewVariables'), 201);
    }

    public function addViewVariables(Event $e) {
        //your code goes here
    }

    // rest of the Module methods goes here...
    //...
    //...
}

How to create simple service using ZF2

reference2

reference3

Azevedo answered 13/11, 2012 at 12:22 Comment(4)
Just as a comment, it would be great if you can shorten your code examples. It is only little helpful to get a bunch of code posted and to figure out everything on your own. Please explain what you're doing (i know it, but questionaire might not)Samathasamau
Thanks Sam for reminding me that only bother to answer a question if you have enough time to answer it precisely. otherwise don't waste your time for quick answer. I will keep this in mind and only answer a question if i would have enough time to answer thoroughly.Azevedo
tks so much for your answer. I can do it now.Rosewater
For clarity this answer worked, I agree it may help to explain more but it does solve the problem.Raama

© 2022 - 2024 — McMap. All rights reserved.