We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Need help with "beforeExecuteRoute"

Hi,

I'm trying to run some code before the route is executed, but cannot figure out how to register my function. In services.php:


$eventsManager = new EventsManager;
$di->setShared('eventsManager', $eventsManager);
$eventsManager->attach(
    'dispatch:beforeExecuteRoute',
    function (Event $event) use ($di) {
        error_log(serialize($event->getType()));
    }
);

but nothing happens, why?

You need also to set this eventsManager on dispatcher.



4.8k

Can you provide an example how to do this?



145.0k
Accepted
answer

For example

$di->setShared('dispatcher', function() {
    $dispatcherr = new Dispatcher();
    $eventsManager = new EventsManager;
    $eventsManager->attach(
        'dispatch:beforeExecuteRoute',
        function (Event $event) use ($di) {
            error_log(serialize($event->getType()));
        }
    );
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});


4.8k

still nothing, this is my code now:

$eventsManager = new EventsManager;

$di->setShared(
    'eventsManager',
    function() use ($eventsManager) {
        $dispatcher = new Dispatcher();
//        $eventsManager = new EventsManager;
        $eventsManager->attach(
            'dispatch:beforeExecuteRoute',
            function (Event $event) {
                error_log('HOHOHO!');
            }
        );
        $dispatcher->setEventsManager($eventsManager);
        return $dispatcher;
    }
);

$di->setShared('router', function () use ($eventsManager) {
    return require APP_PATH . '/config/routes.php';
});
edited Dec '17

dispatcher service, not eventsmanager :) Also you use Application or Micro?



4.8k

oh, thanks.. now it is working. I'm using Application. Now I want to use instead of function a class, but getting error "Class not found"



4.8k

loader.php with

$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir,
        $config->application->layersDir,
        $config->application->helpersDir,
        $config->application->pluginsDir
    ]
)->register();

runs after services.php with my Plugin-Class



4.8k

working fine, the pluginsDir was in wrong place.