Phalcon:在beforeExecuteRoute中获取控制器的实例

时间:2014-11-07 14:17:31

标签: phalcon

如何在beforeExecuteRoute框架的phalcon方法中获取令人兴奋的控制器的实例?

1 个答案:

答案 0 :(得分:4)

令人兴奋的控制器?这一切都取决于他们的兴奋......

但是srsly,您只能从调度程序获取活动控制器的实例,可以像这样访问:

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

如果您将事件处理程序与事件管理器一起使用,那么就像这样:

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

如果您实际上将现有控制器视为复数,那么您需要为控制器实例化添加某种跟踪。您无法通过控制器类中的__construct执行此操作,因为某些天才将某些天才标记为__constructfinal。另一种选择是在beforeExecuteRoutebeforeNotFoundAction事件中添加该跟踪,挖掘the code in the repository以获取详细信息:

// 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();
});