Phalcon: get controller instance in beforeExecuteRoute
Exciting controllers? It all depends on what turns them on ...
But srsly, you can only get an instance of the active controller from a dispatcher that can be accessed, for example:
$controller = $di->getShared('dispatcher')->getActiveController();
If you are using an event handler with an event manager, for example:
$eventManager->attach("dispatch:beforeExecuteRoute", function (Event $event, Dispatcher $dispatcher) {
$controller = $dispatcher->getActiveController();
});
If you actually meant the existing controllers as plural, then you will need to add some kind of tracking to instantiate the controller. You cannot do this via __construct
in your controller classes, because for some reason some genius is tagged __construct
as final
. Another option would be to add this tracking to your event beforeExecuteRoute
and beforeNotFoundAction
, copy the code in the repository for more information:
// Exciting controllers get stored whenever the dispatcher reports if the action was not found
// or when it 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();
});
source to share