Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



1.2k

Can you provide an example how to do this?



114.4k
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;
});


1.2k

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 10d ago

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



1.2k

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"



1.2k

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



1.2k

working fine, the pluginsDir was in wrong place.