我学习ZF2,在登录过程中遇到问题。我有两个模块login和moduleExample。
登录模块基于http://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/
我可以重定向moduleExample到登录路由与条件hasIdentity()在控制器中,但我可以设置重定向到这个模块在一个地方吗?控制器可能会更多。我已经尝试过onBootstrap方法(Module.php),但随后它被重定向到任何地方(在所有模块中)。
在哪里我可以做我所描述的?
可以在一个地方处理登录重定向,一种方法是定义一个自定义事件,该事件在路由事件链中调用。为此,必须在 module .php(最好在身份验证模块中)中添加处理程序:
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$sm = $e->getApplication()->getServiceManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
//attach event here
$eventManager->attach('route', array($this, 'checkUserAuth'), 2);
}
public function checkUserAuth(MvcEvent $e)
{
$router = $e->getRouter();
$matchedRoute = $router->match($e->getRequest());
//this is a whitelist for routes that are allowed without authentication
//!!! Your authentication route must be whitelisted
$allowedRoutesConfig = array(
'auth'
);
if (!isset($matchedRoute) || in_array($matchedRoute->getMatchedRouteName(), $allowedRoutesConfig)) {
// no auth check required
return;
}
$seviceManager = $e->getApplication()->getServiceManager();
$authenticationService = $seviceManager->get('Zend'Authentication'AuthenticationService');
$identity = $authenticationService->getIdentity();
if (! $identity) {
//redirect to login route...
$response = $e->getResponse();
$response->setStatusCode(302);
//this is the login screen redirection url
$url = $e->getRequest()->getBaseUrl() . '/auth/login';
$response->getHeaders()->addHeaderLine('Location', $url);
$app = $e->getTarget();
//dont do anything other - just finish here
$app->getEventManager()->trigger(MvcEvent::EVENT_FINISH, $e);
$e->stopPropagation();
}
}
}
你所尝试的是正确的,那么你只需要这里的这一小部分
$controller = $e->getTarget();
$params = $e->getApplication()->getMvcEvent()->getRouteMatch()->getParams();
if(!$params['controller'] == 'your login conroller path e.g. RouteFolder/Controller/LoginControllerName'){
return $controller->redirect()->toRoute('your redirect route')
}
do a
然后看看它返回什么你就会明白我的意思了 如果你的当前位置是用户登录的控制器print_r (params["控制器"]美元)