Search code examples
zend-framework2zend-framework-mvczend-framework-routing

Do something when Apigility db-connected actions ocurr using Zend Events


I need to do some action once my Apigility db-connected rest service is called (for example the one that creates an entity). I want to do this with Zend Events but I don't know where to start because Apigility has created no code that I can see. Please if someone could provide an example on how to do this that would be great. I'm new to Zend and Apigility. Thanks in advance Alejandro


Solution

  • Code exemple to attach a logic to a MvcEvent

    In module/APIName/Module.php

    <?php
    namespace APIName;
    
    use Zend\Mvc\MvcEvent;
    
    class Module
    {
        public function onBoostrap($e)
        {
            $eventManager        = $e->getApplication()->getEventManager();
            $serviceManager      = $e->getApplication()->getServiceManager();
    
            $eventManager->attach(MvcEvent::EVENT_ROUTE, function($event) use($serviceManager){
                $route  = $event->getRouteMatch()->getMatchedRouteName();
                // Do some stuff, tests, etc...
            }, -1100); // set low priority to be sure that route is defined
        }
    }
    

    Your event will be automatically triggered by the Framework when routing.