Zend Framework动作助手Redirector用法实例详解
本文实例讲述了ZendFramework动作助手Redirector用法。分享给大家供大家参考,具体如下:
Redirector提供另一种实现方式,帮助程序重定向到内部或者外部页面;
转向器(Redirector)助手让你使用一个转向器对象帮助程序重定向到新的URL。与_redirect()方法相比,它具有多项优势。例如能够在转向器对象中预先配置整个站点的行为,或者使用与Zend_Controller_Action::_forward()相似的gotoSimple($action,$controller,$module,$params)接口。
转向器拥有影响重定向行为的大量方法:
setCode()设置重定向过程中使用的HTTP响应码。
setExit()在重定向后强制执行exit()方法。默认已设定。
setGotoSimple()设置默认的URL,当没有提供参数给gotoSimple()方法时转向该URL。可以使用类似Zend_Controller_Action::_forward()的API:setGotoSimple($action,$controller=null,$module=null,array$params=array());
setGotoRoute()设置基于一个注册路由器的URL。通过传入一个键/值数组和一个路由器名,它将根据路由器的类型和定义来组织URL。
setGotoUrl()设置默认的URL,当没有参数传入gotoUrl(),将使用该URL。接受单个URL字符串。
setPrependBase()在setGotoUrl()、gotoUrl()或者gotoUrlAndExit()指定的URL前面,加入请求对象的基地址(baseURL)。
setUseAbsoluteUri()强制转向器在重定向时使用绝对的URI。当该选项设定后,将使用$_SERVER['HTTP_HOST']、$_SERVER['SERVER_PORT']和$_SERVER['HTTPS']以及重定向方法指定的URL,来形成一个完整的URI。该选项目前默认关闭,将来的版本可能会默认开启。
此外,转向器中还有大量方法来执行实际的重定向。
gotoSimple()使用setGotoSimple()(类似_forward()的API)来构建URL并执行重定向。
gotoRoute()使用setGotoRoute()(路由组装route-assembly)来构建URL并执行重定向。
gotoUrl()使用setGotoUrl()URL字符串)来构造URL并执行重定向。
最后,你可以在任何时刻使用getRedirectUrl()确定当前的重定向URL。
基础用例
Example#5设定选项
这个例子改变了几个选项,包括设定重定向时使用的HTTP状态码为303,重定向时不默认退出,以及定义了默认的URL供重定向使用。
classSomeControllerextendsZend_Controller_Action { /** *Redirector-definedforcodecompletion * *@varZend_Controller_Action_Helper_Redirector */ protected$_redirector=null; publicfunctioninit() { $this->_redirector=$this->_helper->getHelper('Redirector'); //Setthedefaultoptionsfortheredirector //Sincetheobjectisregisteredinthehelperbroker,these //becomerelevantforallactionsfromthispointforward $this->_redirector->setCode(303) ->setExit(false) ->setGotoSimple("this-action", "some-controller"); } publicfunctionmyAction() { /*dosomestuff*/ //RedirecttoapreviouslyregisteredURL,andforceanexit //tooccurwhendone: $this->_redirector->redirectAndExit(); return;//neverreached } }
Example#6使用默认设定
这个例子假定使用默认设定,也就意味着任何重定向将导致立即退出。
//ALTERNATIVEEXAMPLE classAlternativeControllerextendsZend_Controller_Action { /** *Redirector-definedforcodecompletion * *@varZend_Controller_Action_Helper_Redirector */ protected$_redirector=null; publicfunctioninit() { $this->_redirector=$this->_helper->getHelper('Redirector'); } publicfunctionmyAction() { /*dosomestuff*/ $this->_redirector ->gotoUrl('/my-controller/my-action/param1/test/param2/test2'); return;//neverreachedsincedefaultistogotoandexit } }
Example#7使用goto()的_forward()API
gotoSimple()'sAPI模拟了Zend_Controller_Action::_forward()。主要的不同在于它通过传入的参数构造URL,使用默认路由器的默认格式:module/:controller/:action/*。然后重定向而不是继续动作链循环。
classForwardControllerextendsZend_Controller_Action { /** *Redirector-definedforcodecompletion * *@varZend_Controller_Action_Helper_Redirector */ protected$_redirector=null; publicfunctioninit() { $this->_redirector=$this->_helper->getHelper('Redirector'); } publicfunctionmyAction() { /*dosomestuff*/ //Redirectto'my-action'of'my-controller'inthecurrent //module,usingtheparamsparam1=>testandparam2=>test2 $this->_redirector->gotoSimple('my-action', 'my-controller', null, array('param1'=>'test', 'param2'=>'test2' ) ); } }
Example#8通过gotoRoute()使用路由组装(routeassembly)
下面的例子使用了路由器的assemble()方法,基于传入参数的关联数组来创建URL。假定下面的路由已经注册:
$route=newZend_Controller_Router_Route( 'blog/:year/:month/:day/:id', array('controller'=>'archive', 'module'=>'blog', 'action'=>'view') ); $router->addRoute('blogArchive',$route);
给定一个数组,其中年份为2006,月份为4,日期为24,id为42,据此可以组装URL/blog/2006/4/24/42。
classBlogAdminControllerextendsZend_Controller_Action { /** *Redirector-definedforcodecompletion * *@varZend_Controller_Action_Helper_Redirector */ protected$_redirector=null; publicfunctioninit() { $this->_redirector=$this->_helper->getHelper('Redirector'); } publicfunctionreturnAction() { /*dosomestuff*/ //Redirecttoblogarchive.BuildsthefollowingURL: ///blog/2006/4/24/42 $this->_redirector->gotoRoute( array('year'=>2006, 'month'=>4, 'day'=>24, 'id'=>42), 'blogArchive' ); } }
Zend_Controller_Action_Helper_Redirector的源码。
通过源代码不难看出实现方法,以及常见的使用方法。
<?php /** *@seeZend_Controller_Action_Helper_Abstract */ require_once'Zend/Controller/Action/Helper/Abstract.php'; /** *@categoryZend *@packageZend_Controller *@subpackageZend_Controller_Action_Helper *@copyrightCopyright(c)2005-2011ZendTechnologiesUSAInc.(http://www.zend.com) *@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense */ classZend_Controller_Action_Helper_RedirectorextendsZend_Controller_Action_Helper_Abstract { /** *HTTPstatuscodeforredirects *@varint */ protected$_code=302; /** *Whetherornotcallsto_redirect()shouldexitscriptexecution *@varboolean */ protected$_exit=true; /** *Whetherornot_redirect()shouldattempttoprependthebaseURLtothe *passedURL(ifit'sarelativeURL) *@varboolean */ protected$_prependBase=true; /** *Urltowhichtoredirect *@varstring */ protected$_redirectUrl=null; /** *WhetherornottouseanabsoluteURIwhenredirecting *@varboolean */ protected$_useAbsoluteUri=false; /** *Whetherornottoclosethesessionbeforeexiting *@varboolean */ protected$_closeSessionOnExit=true; /** *RetrieveHTTPstatuscodetoemiton{@link_redirect()}call * *@returnint */ publicfunctiongetCode() { return$this->_code; } /** *ValidateHTTPstatusredirectcode * *@paramint$code *@throwsZend_Controller_Action_ExceptiononinvalidHTTPstatuscode *@returntrue */ protectedfunction_checkCode($code) { $code=(int)$code; if((300>$code)||(307<$code)||(304==$code)||(306==$code)){ require_once'Zend/Controller/Action/Exception.php'; thrownewZend_Controller_Action_Exception('InvalidredirectHTTPstatuscode('.$code.')'); } returntrue; } /** *RetrieveHTTPstatuscodefor{@link_redirect()}behaviour * *@paramint$code *@returnZend_Controller_Action_Helper_RedirectorProvidesafluentinterface */ publicfunctionsetCode($code) { $this->_checkCode($code); $this->_code=$code; return$this; } /** *Retrieveflagforwhetherornot{@link_redirect()}willexitwhenfinished. * *@returnboolean */ publicfunctiongetExit() { return$this->_exit; } /** *Retrieveexitflagfor{@link_redirect()}behaviour * *@paramboolean$flag *@returnZend_Controller_Action_Helper_RedirectorProvidesafluentinterface */ publicfunctionsetExit($flag) { $this->_exit=($flag)?true:false; return$this; } /** *Retrieveflagforwhetherornot{@link_redirect()}willprependthe *baseURLonrelativeURLs * *@returnboolean */ publicfunctiongetPrependBase() { return$this->_prependBase; } /** *Retrieve'prependbase'flagfor{@link_redirect()}behaviour * *@paramboolean$flag *@returnZend_Controller_Action_Helper_RedirectorProvidesafluentinterface */ publicfunctionsetPrependBase($flag) { $this->_prependBase=($flag)?true:false; return$this; } /** *Retrieveflagforwhetherornot{@linkredirectAndExit()}shallclosethesessionbefore *exiting. * *@returnboolean */ publicfunctiongetCloseSessionOnExit() { return$this->_closeSessionOnExit; } /** *Setflagforwhetherornot{@linkredirectAndExit()}shallclosethesessionbeforeexiting. * *@paramboolean$flag *@returnZend_Controller_Action_Helper_RedirectorProvidesafluentinterface */ publicfunctionsetCloseSessionOnExit($flag) { $this->_closeSessionOnExit=($flag)?true:false; return$this; } /** *ReturnuseabsoluteURIflag * *@returnboolean */ publicfunctiongetUseAbsoluteUri() { return$this->_useAbsoluteUri; } /** *SetuseabsoluteURIflag * *@paramboolean$flag *@returnZend_Controller_Action_Helper_RedirectorProvidesafluentinterface */ publicfunctionsetUseAbsoluteUri($flag=true) { $this->_useAbsoluteUri=($flag)?true:false; return$this; } /** *Setredirectinresponseobject * *@returnvoid */ protectedfunction_redirect($url) { if($this->getUseAbsoluteUri()&&!preg_match('#^(https?|ftp)://#',$url)){ $host=(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:''); $proto=(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off")?'https':'http'; $port=(isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80); $uri=$proto.'://'.$host; if((('http'==$proto)&&(80!=$port))||(('https'==$proto)&&(443!=$port))){ //donotappendifHTTP_HOSTalreadycontainsport if(strrchr($host,':')===false){ $uri.=':'.$port; } } $url=$uri.'/'.ltrim($url,'/'); } $this->_redirectUrl=$url; $this->getResponse()->setRedirect($url,$this->getCode()); } /** *RetrievecurrentlysetURLforredirect * *@returnstring */ publicfunctiongetRedirectUrl() { return$this->_redirectUrl; } /** *DetermineifthebaseUrlshouldbeprepended,andprependifnecessary * *@paramstring$url *@returnstring */ protectedfunction_prependBase($url) { if($this->getPrependBase()){ $request=$this->getRequest(); if($requestinstanceofZend_Controller_Request_Http){ $base=rtrim($request->getBaseUrl(),'/'); if(!empty($base)&&('/'!=$base)){ $url=$base.'/'.ltrim($url,'/'); }else{ $url='/'.ltrim($url,'/'); } } } return$url; } /** *SetaredirectURLoftheform/module/controller/action/params * *@paramstring$action *@paramstring$controller *@paramstring$module *@paramarray$params *@returnvoid */ publicfunctionsetGotoSimple($action,$controller=null,$module=null,array$params=array()) { $dispatcher=$this->getFrontController()->getDispatcher(); $request=$this->getRequest(); $curModule=$request->getModuleName(); $useDefaultController=false; if(null===$controller&&null!==$module){ $useDefaultController=true; } if(null===$module){ $module=$curModule; } if($module==$dispatcher->getDefaultModule()){ $module=''; } if(null===$controller&&!$useDefaultController){ $controller=$request->getControllerName(); if(empty($controller)){ $controller=$dispatcher->getDefaultControllerName(); } } $params[$request->getModuleKey()]=$module; $params[$request->getControllerKey()]=$controller; $params[$request->getActionKey()]=$action; $router=$this->getFrontController()->getRouter(); $url=$router->assemble($params,'default',true); $this->_redirect($url); } /** *BuildaURLbasedonaroute * *@paramarray$urlOptions *@paramstring$nameRoutename *@paramboolean$reset *@paramboolean$encode *@returnvoid */ publicfunctionsetGotoRoute(array$urlOptions=array(),$name=null,$reset=false,$encode=true) { $router=$this->getFrontController()->getRouter(); $url=$router->assemble($urlOptions,$name,$reset,$encode); $this->_redirect($url); } /** *SetaredirectURLstring * *Bydefault,emitsa302HTTPstatusheader,prependsbaseURLasdefined *inrequestobjectifurlisrelative,andhaltsscriptexecutionby *callingexit(). * *$optionsisanoptionalassociativearraythatcanbeusedtocontrol *redirectbehaviour.Theavailableoptionkeysare: *-exit:booleanflagindicatingwhetherornottohaltscriptexecutionwhendone *-prependBase:booleanflagindicatingwhetherornottoprependthebaseURLwhenarelativeURLisprovided *-code:integerHTTPstatuscodetousewithredirect.Shouldbebetween300and307. * *_redirect()setstheLocationheaderintheresponseobject.Ifyouset *theexitflagtofalse,youcanoverridethisheaderlaterincode *execution. * *Iftheexitflagistrue(truebydefault),_redirect()willwriteand *closethecurrentsession,ifany. * *@paramstring$url *@paramarray$options *@returnvoid */ publicfunctionsetGotoUrl($url,array$options=array()) { //preventheaderinjections $url=str_replace(array("\n","\r"),'',$url); if(null!==$options){ if(isset($options['exit'])){ $this->setExit(($options['exit'])?true:false); } if(isset($options['prependBase'])){ $this->setPrependBase(($options['prependBase'])?true:false); } if(isset($options['code'])){ $this->setCode($options['code']); } } //IfrelativeURL,decideifweshouldprependbaseURL if(!preg_match('|^[a-z]+://|',$url)){ $url=$this->_prependBase($url); } $this->_redirect($url); } /** *Performaredirecttoanaction/controller/modulewithparams * *@paramstring$action *@paramstring$controller *@paramstring$module *@paramarray$params *@returnvoid */ publicfunctiongotoSimple($action,$controller=null,$module=null,array$params=array()) { $this->setGotoSimple($action,$controller,$module,$params); if($this->getExit()){ $this->redirectAndExit(); } } /** *Performaredirecttoanaction/controller/modulewithparams,forcinganimmdiateexit * *@parammixed$action *@parammixed$controller *@parammixed$module *@paramarray$params *@returnvoid */ publicfunctiongotoSimpleAndExit($action,$controller=null,$module=null,array$params=array()) { $this->setGotoSimple($action,$controller,$module,$params); $this->redirectAndExit(); } /** *Redirecttoaroute-basedURL * *Usesroute'sassemblemethodtobuildtheURL;routeisspecifiedby$name; *defaultrouteisusedifnoneprovided. * *@paramarray$urlOptionsArrayofkey/valuepairsusedtoassembleURL *@paramstring$name *@paramboolean$reset *@paramboolean$encode *@returnvoid */ publicfunctiongotoRoute(array$urlOptions=array(),$name=null,$reset=false,$encode=true) { $this->setGotoRoute($urlOptions,$name,$reset,$encode); if($this->getExit()){ $this->redirectAndExit(); } } /** *Redirecttoaroute-basedURL,andimmediatelyexit * *Usesroute'sassemblemethodtobuildtheURL;routeisspecifiedby$name; *defaultrouteisusedifnoneprovided. * *@paramarray$urlOptionsArrayofkey/valuepairsusedtoassembleURL *@paramstring$name *@paramboolean$reset *@returnvoid */ publicfunctiongotoRouteAndExit(array$urlOptions=array(),$name=null,$reset=false) { $this->setGotoRoute($urlOptions,$name,$reset); $this->redirectAndExit(); } /** *Performaredirecttoaurl * *@paramstring$url *@paramarray$options *@returnvoid */ publicfunctiongotoUrl($url,array$options=array()) { $this->setGotoUrl($url,$options); if($this->getExit()){ $this->redirectAndExit(); } } /** *SetaURLstringforaredirect,performredirect,andimmediatelyexit * *@paramstring$url *@paramarray$options *@returnvoid */ publicfunctiongotoUrlAndExit($url,array$options=array()) { $this->setGotoUrl($url,$options); $this->redirectAndExit(); } /** *exit():Performexitforredirector * *@returnvoid */ publicfunctionredirectAndExit() { if($this->getCloseSessionOnExit()){ //Closesession,ifstarted if(class_exists('Zend_Session',false)&&Zend_Session::isStarted()){ Zend_Session::writeClose(); }elseif(isset($_SESSION)){ session_write_close(); } } $this->getResponse()->sendHeaders(); exit(); } /** *direct():Performhelperwhencalledas *$this->_helper->redirector($action,$controller,$module,$params) * *@paramstring$action *@paramstring$controller *@paramstring$module *@paramarray$params *@returnvoid */ publicfunctiondirect($action,$controller=null,$module=null,array$params=array()) { $this->gotoSimple($action,$controller,$module,$params); } /** *Overloading * *Overloadingforold'goto','setGoto',and'gotoAndExit'methods * *@paramstring$method *@paramarray$args *@returnmixed *@throwsZend_Controller_Action_Exceptionforinvalidmethods */ publicfunction__call($method,$args) { $method=strtolower($method); if('goto'==$method){ returncall_user_func_array(array($this,'gotoSimple'),$args); } if('setgoto'==$method){ returncall_user_func_array(array($this,'setGotoSimple'),$args); } if('gotoandexit'==$method){ returncall_user_func_array(array($this,'gotoSimpleAndExit'),$args); } require_once'Zend/Controller/Action/Exception.php'; thrownewZend_Controller_Action_Exception(sprintf('Invalidmethod"%s"calledonredirector',$method)); } }
更多关于zend相关内容感兴趣的读者可查看本站专题:《ZendFrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。