假设我们有一个名为Cart的模块,并希望在满足某些条件时重定向用户。我想在模块启动阶段,在应用程序到达任何控制器之前,放置一个重定向。
模块代码如下:
<?php
namespace Cart;
class Module
{
function onBootstrap() {
if (somethingIsTrue()) {
// redirect
}
}
}
?>
我想使用Url控制器插件,但似乎控制器实例在这个阶段不可用,至少我不知道如何得到它。
Thanks in advance
这应该完成必要的工作:
<?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;
}
}
}
?>
当然会给您一个错误,因为您必须将侦听器附加到事件上。在下面的示例中,我使用SharedManager,并将侦听器附加到AbstractActionController
。
当然,您可以将侦听器附加到另一个事件。下面只是一个工作示例,向您展示它是如何工作的。更多信息请访问http://framework.zend.com/manual/2.1/en/modules/zend.event-manager.event-manager.html。
public function onBootstrap($e)
{
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend'Mvc'Controller'AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
if (something.....) {
$controller->plugin('redirect')->toRoute('yourroute');
}
}, 100);
}
页面重定向错误
public function onBootstrap($e) {
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend'Mvc'Controller'AbstractActionController', 'dispatch', function($e) {
if(someCondition==true) {
$controller->plugin('redirect')->toRoute('myroute');
}
}
你能试试吗?
$front = Zend_Controller_Front::getInstance();
$response = new Zend_Controller_Response_Http();
$response->setRedirect('/profile');
$front->setResponse($response);