开发者

Redirect in Front Controller plugin Zend

I'm trying to centralise my redirects (based on authentication and various other states) into a front controller plugin. So far I've tried:

    $this->setRequest(new Zend_Controller_Request_Http('my_url'));

at various points in the plugin (i.e. from routeStartup to dispatchLoopShutdown) and also:

    $th开发者_如何学Cis->setResponse(new Zend_Controller_Response_Http('my_url'));

Can anyone offer some assistance on this, or point me in the direction of a tutorial?


The easiest way would be to use ZF's Redirect ActionHelper

    $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
    $r->gotoUrl('/some/url')->redirectAndExit();

Alternatively instantiate it without the HelperBroker

    $r = new Zend_Controller_Action_Helper_Redirector;
    $r->gotoUrl('/some/url')->redirectAndExit();

The ActionHelper provides an API solely concerned about redirecting through a number of methods, like gotoRoute, gotoUrl, gotoSimple, which you can use depending on your desired UseCase.

Internally, the ActionHelper uses the APIs of Response and Router to do the redirect though, so you can also use their methods directly, e.g.

    $request->setModuleName('someModule')
            ->setControllerName('someController')
            ->setActionName('someAction');

or

    $response->setRedirect('/some/url', 200);

Further reading:

  • http://devzone.zend.com/article/3372-Front-Controller-Plugins-in-Zend-Framework
  • http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
  • http://framework.zend.com/manual/en/zend.controller.response.html
  • http://framework.zend.com/manual/en/zend.controller.plugins.html
  • http://framework.zend.com/apidoc/core
  • http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Controller/


If you are looking to redirect if the user is not logged it, the first parameter of dispatchLoopStartup() is a handle to the request object.

public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
    if(!Zend_Auth::getInstance()->hasIdentity())
    {
        $request->setControllerName('auth');
        $request->setActionName('login');
        // Set the module if you need to as well.
    }
}


If you want to redirect in the index page then this should suffice.

public function preDispatch(Zend_Controller_Request_Abstract $request)
{
    if(!Zend_Auth::getInstance()->hasIdentity())
    {
          $baseUrl = new Zend_View_Helper_BaseUrl();
          $this->getResponse()->setRedirect($baseUrl->baseUrl());
    }
}

If you want to redirect somewhere else then just change the parameter in the setRedirect() function

Thanks! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜