详解php框架Yaf路由重写!
通常为了友好的URL格式,会进行站点URL的重写,可以在webserver(Nginx)的配置中进行rewrite,也可在在程序端进行
以下使用Yaf框架进行URL的重写,进行一些整理,方便日后查看
YAF的URL重写方式主要有以下几种,可以综合使用
方式1:在配置文件中进行
;arewriteroutematchrequest/product/*/* routes.route_name.type="rewrite" routes.route_name.match="/product/:name/:value" routes.route_name.route.controller=product routes.route_name.route.action=info ;aregexroutematchrequest/list/*/* routes.route_name1.type="regex" routes.route_name1.match="#^list/([^/]*)/([^/]*)#" routes.route_name1.route.controller=Index routes.route_name1.route.action=action routes.route_name1.map.1=name routes.route_name1.map.2=value ;asimpleroutematch/**?c=controller&a=action&m=module routes.route_name2.type="simple" routes.route_name2.controller=c routes.route_name2.module=m routes.route_name2.action=a ;asimpleroutermatch/**?r=PATH_INFO routes.route_name3.type="supervar" routes.route_name3.varname=r ;amaproutematchanyrequesttocontroller routes.route_name4.type="map" routes.route_name4.controllerPrefer=TRUE routes.route_namer.delimiter="#!"
之后在Bootstrap.php中添加初始化函数,函数名可按自己需求取,必需以_开头才会被调用
getConfig(); Yaf_Registry::set("config",$config); } publicfunction_initRoute(Yaf_Dispatcher$dispatcher){ $router=$dispatcher->getRouter(); /** *wecanaddsomepre-definedroutesinapplication.ini */ $router->addConfig(Yaf_Registry::get("config")->routes); /** *addaRewriteroute,thenforarequesturi: *http://***/product/list/22/foo *willbematchedbythisroute,andresult: * *[module]=> *[controller]=>product *[action]=>info *[method]=>GET *[params:protected]=>Array *( *[id]=>22 *[name]=>foo *) * */ $route=newYaf_Route_Rewrite( "/product/list/:id/:name", array( "controller"=>"product", "action"=>"info", ) ); $router->addRoute('dummy',$route); } ?>
方式2:直接在程序中,以数组方式配置
以下函数是放在Bootstrap.php中
publicfunction_initRoute(Ap_Dispatcher$dispatcher){ //在这里注册自己的路由协议,默认使用static路由 $router=Ap_Dispatcher::getInstance()->getRouter(); $routeConfig=array( $router=Ap_Dispatcher::getInstance()->getRouter(); $routeConfig=array( "item"=>array( "type"=>"regex", "match"=>"#^/(software|game)/(.*).html$#", "route"=>array('action'=>'item'), "map"=>array(1=>'data_type',2=>'docid'), ), //正则匹配 "category"=>array( "type"=>"regex", "match"=>"#^/(software|game|video)/(.*)/(list_(.*).html)?$#", "route"=>array('action'=>'list'), "map"=>array(1=>'data_type',2=>'cid',4=>'page_num'), ), //使用动态结果:a表示action "name"=>array( "type"=>"rewrite",//Yaf_Route_Rewriteroute "match"=>"/user-list/:a/:id",//matchonly/user-list/开头的 "route"=>array( 'controller'=>"user",//routetousercontroller, 'action'=>":a",//使用动态的action ), ), ); $router->addConfig(newAp_Config_Simple($routeConfig)); }
方式3:
/** *AddarewriteroutetoYaf_Routerroutestack */ Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name", newYaf_Route_rewrite( "/product/:name/:id/*",//matchrequesturileading"/product" array( 'controller'=>"product",//routetoproductcontroller, ), ) );
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。