Zend框架2:如何从插件重定向?

I worte a plugin IdentityPlugin to check login status of a user. If the user session gets logout, I want to redirect them to login page. My code is given below.

public function checkLogin($logout=true,$next='login'){        
    if($this->auth->hasIdentity()){            
    }elseif ($logout){
        return $this->getController()->redirect()->toRoute($next);
    }
}

in my controller

// Check identity, if not found- redirect to login
$this->IdentityPlugin()->checkLogin();

Any idea?

You're returning a response to the controller but you're not returning it from the controller itself.

For example you could try this is your controller:

$check = $this->IdentityPlugin()->checkLogin();
if ($check instanceof Response) {
    return $check;
}

A more complex solution could be to stop the propagation of the controller's MvcEvent, set whatever response you want, and return directly.

Hi you need to config you plugin in factories in module.config.php and pass service manager to __construct, like below:

'controller_plugins' => array(

    'factories' => array(
        'CheckLogin' => function($sm){
            $checkLogin  = new Application\Plugin\CheckLogin($sm);
            return $checkLogin;
        },
    ),  
),

Then in your plugin you will be able to call all you need using service Manager:

namespace Application\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class CheckLogin extends AbstractPlugin 
{


    public function __construct($sm)
    {

        $auth = $sm->getServiceLocator()->get("Zend\Authentication\AuthenticationService");

        if( !$auth->hasIdentity()){
            $sm->getController()->plugin('redirect')->toUrl('/login');
        }

    }        

}