Art*_*rev 11 php redirect zend-framework2
假设我们有一个名为Cart的模块,并且如果满足某些条件,则希望重定向用户.我想在应用程序到达任何控制器之前在模块引导阶段放置重定向.
所以这是模块代码:
<?php
namespace Cart;
class Module
{
function onBootstrap() {
if (somethingIsTrue()) {
// redirect
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我想使用Url控制器插件,但似乎控制器实例在此阶段不可用,至少我不知道如何获取它.
提前致谢
yec*_*bbi 31
这应该做必要的工作:
<?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;
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
当然它会给你一个错误,因为你必须将你的监听器附加到一个事件.在下面的示例中,我使用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);
}
Run Code Online (Sandbox Code Playgroud)
Nan*_*r V -4
你能试试这个吗?
$front = Zend_Controller_Front::getInstance();
$response = new Zend_Controller_Response_Http();
$response->setRedirect('/profile');
$front->setResponse($response);
Run Code Online (Sandbox Code Playgroud)