【问题标题】:Phalcon MVC dispatcher - cancelling action from beforeDispatchPhalcon MVC 调度程序 - 从 beforeDispatch 取消操作
【发布时间】:2014-04-23 16:26:17
【问题描述】:

匿名用户正在访问以下需要经过身份验证的用户的 URL:/myprofile/settings。我希望能够中止 MVC 调度循环并将用户发送到登录位置。

代码:

$evt = $di->getShared('dispatcher')->getEventsManager();
$evt->attach('dispatch', new AccessControl\Security($di));

安全类:

/**
 * This action is executed before execute any action in the application
 */
public function beforeDispatch(Event $event, Dispatcher $dispatcher)
{
    // User is not authenticated, access should be denied.
    $this->response->redirect('/signin');
}

问题。我如何告诉调度员跳过路由到myprofile Controller 和settings Action 而转储响应(将重定向到/signin)。

$event->stop() 不起作用。

谢谢!

【问题讨论】:

    标签: php phalcon


    【解决方案1】:

    解决办法如下:

    public function beforeDispatch(Event $event, Dispatcher $dispatcher)
    {
        // User is not authenticated, access should be denied.
        $this->response->redirect('/signin');
    
        //Returning "false" we tell to the dispatcher to stop the current operation
        return false;
    }
    

    http://docs.phalconphp.com/en/latest/reference/tutorial-invo.html 了解更多信息。

    【讨论】:

      【解决方案2】:

      为避免涉及额外的往返重定向,您也可以将请求转移到您的登录操作。

      此代码取自一个高度定制的应用程序,因此它可能无法为您开箱即用,但您会明白的(它还将请求的 url 添加为调度程序参数,因此您可以在隐藏字段中输出它您的登录表单并在成功登录时重定向用户):

      public function beforeDispatchLoop(Event $event, Dispatcher $dispatcher)
      {
          if (! $this->auth->hasIdentity() && ! $this->auth->authenticateViaRememberMe()) {
              $dispatcher->setModuleName('login');
              $dispatcher->setControllerName('Login');
              $dispatcher->setActionName('login');
              $dispatcher->setNamespaceName('Login\Controller');
              $dispatcher->setParam('goto', ltrim($_SERVER["REQUEST_URI"], '/'));
              $this->view->setViewsDir($this->registry->directories->modules . 'Login/View');
              return $dispatcher->forward(array());
          }
      }
      

      【讨论】:

        【解决方案3】:

        我来这里是为了寻找一个类似的问题,即返回 false 并没有像 'temuri' 建议的那样起作用。这是因为我在 'dispatcher:beforeExecuteRoute' 事件上有多个 'listener'。

        该错误已知于:https://github.com/phalcon/cphalcon/issues/14675

        要解决这个问题,也可以调用 $event->stop();在返回 false 以解决此问题之前。

        【讨论】:

          猜你喜欢
          • 2012-05-07
          • 1970-01-01
          • 1970-01-01
          • 2018-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-24
          相关资源
          最近更新 更多