【问题标题】:Phalcon : get instance of controller in beforeExecuteRoutePhalcon:在 beforeExecuteRoute 中获取控制器实例
【发布时间】:2014-11-07 14:17:31
【问题描述】:

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

【问题讨论】:

    标签: phalcon


    【解决方案1】:

    令人兴奋的控制器?这完全取决于他们兴奋的原因……

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

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

    如果您将事件处理程序与事件管理器一起使用,则比这样:

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

    如果您实际上是指现有控制器是复数形式,那么您需要为控制器实例添加某种跟踪。您不能通过控制器类中的__construct 来执行此操作,因为出于某种原因,某些天才将__construct 标记为final。另一种选择是在您的beforeExecuteRoute 和beforeNotFoundAction 事件中添加该跟踪,请挖掘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();
    });
    

    【讨论】:

      【解决方案2】:

      如果你使用的是 Phalcon\Mvc\Micro,很抱歉告诉你,很难得到正确答案。我之前也遇到过类似的问题,所以我使用 PHP 的反射机制分析了 $event 和 $app 和得出以下答案:

      <?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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-02
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多