假设我们有一个名为Cart的模块,如果满足某些条件,则要重定向用户.
我想在模块引导阶段放置重定向,在应用程序到达任何控制器之前.
我想在模块引导阶段放置重定向,在应用程序到达任何控制器之前.
所以这里是模块代码:
<?PHP namespace Cart; class Module { function onBootstrap() { if (somethingIsTrue()) { // redirect } } } ?>
我想使用Url控制器插件,但似乎控制器实例在这个阶段是不可用的,至少我不知道如何得到它.
提前致谢
这应该做必要的工作:
<?PHP namespace Cart; use Zend\Mvc\MvcEvent; class Module { function onBootstrap(MvcEvent $e) { if (somethingIsTrue()) { // Assuming your login route has a name 'login',this will do the assembly // (you can also use directly $url=/path/to/login) $url = $e->getRouter()->assemble(array(),array('name' => 'login')); $response=$e->getResponse(); $response->getHeaders()->addHeaderLine('Location',$url); $response->setStatusCode(302); $response->sendHeaders(); // When an MvcEvent Listener returns a Response object,// It automatically short-circuit the Application running // -> true only for Route Event propagation see Zend\Mvc\Application::run // To avoid additional processing // we can attach a listener for Event Route with a high priority $stopCallBack = function($event) use ($response){ $event->stopPropagation(); return $response; }; //Attach the "break" as a listener with a high priority $e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE,$stopCallBack,-10000); return $response; } } } ?>