ZF2 重定向到具有控制器操作的路由

ZF2 Redirect to route with controller action

我在 module.config.php 中添加了:

    'logout' => array(
        'type' => 'literal',
        'options' => array(
            'route'    => '/logout',
            'defaults' => array(
                '__NAMESPACE__' => 'Users\Controller',
                'controller'    => 'Index',
                'action'        => 'logout',
            ),
        ),
    ),

在IndexController.php中添加:

public function logoutAction() {
    $this->getSessionStorage()->forgetMe();
    $this->getAuthService()->getStorage()->clear("email");
    return $this->redirect()->toRoute('users', array('controller' => 'Login', 'action' => 'index'));
}

并且总是重定向到 http://localhost/users but should to http://localhost/users/login/index

当您使用 Zend\Mvc\Controller\Plugin\Redirect::toRoute() 时,第一个参数是您在 module.config.php 中定义的路由的名称。例如你提到的路线定义为 logout.

'logout' => array(
    'type' => 'literal',
    'options' => array(
        'route'    => '/logout',
        'defaults' => array(
            '__NAMESPACE__' => 'Users\Controller',
            'controller'    => 'Index',
            'action'        => 'logout',
        ),
    ),
),

因此要重定向到此路由,请使用以下行。

$this->redirect()->toRoute('logout')

不需要提供控制器 and/or 操作作为第二个参数,因为您已经在路由的 options 处配置了它。