user3368481
user3368481

Reputation:

Phalcon : get instance of controller in beforeExecuteRoute

How can i get instance of the exciting controllers in beforeExecuteRoute method of the phalcon framework?

Upvotes: 3

Views: 1457

Answers (2)

shao ying wang
shao ying wang

Reputation: 11

If you're using Phalcon\Mvc\Micro, I'm sorry to tell you that it's hard to get the right answer.I had a similar problem before, so I analyzed $event and $app using PHP's reflection mechanism and came up with the following answer:

<?php

    $eventsManager = new \Phalcon\Events\Manager();
    $eventsManager->attach(
        'micro:beforeExecuteRoute',
        function (\Phalcon\Events\Event $event, $app) {
            $controllerName = $event->getSource()->getActiveHandler()[0]->getDefinition();
            $actionName = $event->getSource()->getActiveHandler()[1];
        }
    );

    $app = new \Phalcon\Mvc\Micro($di);
    $app->setEventsManager($eventsManager);

Upvotes: 0

Ian Bytchek
Ian Bytchek

Reputation: 9085

Exciting controllers? It all depends on what excited them…

But srsly, you can only get the instance of the active controller from the dispatcher, that can be accessed like this:

$controller = $di->getShared('dispatcher')->getActiveController();

If you are using event handler with event manager, than like this:

$eventManager->attach("dispatch:beforeExecuteRoute", function (Event $event, Dispatcher $dispatcher) {
    $controller = $dispatcher->getActiveController();
});

If you actually meant existing controllers as plural, then you'd need to add some sort of tracking for controller instantiation. You can't do this via __construct in your controller classes, because for some reason some genius marked __construct as final. The other option would be to add that tracking in your beforeExecuteRoute and beforeNotFoundAction event, dig the code in the repository for details:

// Exciting controllers get stored whenever the dispatcher reports if the action was not found
// or when it's ready to dispatch. Note, if a controller gets created outside the dispatcher
// it will not be tracked, though in real life that should never happen.

$controller = [];

$eventManager->attach("dispatch:beforeNotFoundAction", function (Event $event, Dispatcher $dispatcher) {
    $controllers[] = $dispatcher->getActiveController();
});

$eventManager->attach("dispatch:beforeExecuteRoute", function (Event $event, Dispatcher $dispatcher) {
    $controllers[] = $dispatcher->getActiveController();
});

Upvotes: 4

Related Questions