使用路由既能够让之很复杂,同时也能让它很简单,这是归于你的应用。然而使用一个路由是很简单的,你能够添加你的路由协议给路由器,这样就OK了! 不一样的路由协议以下所示:php
Yaf_Route_Simple
html
Yaf_Route_Static
this
Yaf_Route_Regex
router
咱们这里就写个简单的几个路由协议得demohtm
首先在配置文件中添加路由
;自定义路由
;顺序很重要
routes.regex.type="regex"
routes.regex.match="#^/list/([a-z]+)[-]?([1-9]+)?$#"
routes.regex.route.controller=Index
routes.regex.route.action=action
routes.regex.map.1=name
routes.regex.map.2=pageget
;添加一个名为simple的路由协议
routes.simple.type="simple"
routes.simple.controller=c
routes.simple.module=m
routes.simple.action=a
;添加一个名为supervar的路由协议
routes.supervar.type="supervar"
routes.supervar.varname=r
[product : common]
;product节是Yaf默认关心的节, 添加一个名为rewrite的路由协议
routes.rewrite.type="rewrite"
routes.rewrite.match="/product/:name/:value"
routes.rewrite.controller=c
routes.rewrite.module=m
routes.rewrite.action=a
而后再Bootstrap中 添加路由的定义
public function _initRoute(Yaf_Dispatcher $dispatcher) {
//经过派遣器获得默认的路由器
$router = Yaf_Dispatcher::getInstance()->getRouter();
/** 添加配置中的路由 */
$router->addConfig(Yaf_Registry::get("config")->routes);
//Yaf_Route_Simple
//请求方式 index.php?m=module&c=controller&a=action
//配置规则
//列如 ?c=index&a=test 方法index控制器下的test方法
$route = new Yaf_Route_Simple("m", "c", "a");
/** 添加规则*/
$router->addRoute("name", $route);
//Yaf_Route_Supervar
//请求方式 index.php?r=/module/controller/action
$route = new Yaf_Route_Supervar("r");
$router->addRoute("name", $route);
/**
* 对于请求request_uri为"/ap/foo/bar"
* base_uri为"/ap"
* 则最后参加路由的request_uri为"/foo/bar"
* 而后, 经过对URL分段, 获得以下分节
* foo, bar
* 组合在一块儿之后, 获得路由结果foo_bar
* 而后根据在构造Yaf_Route_Map的时候, 是否指明了控制器优先,
* 若是没有, 则把结果当作是动做的路由结果
* 不然, 则认为是控制器的路由结果
* 默认的, 控制器优先为FALSE
*/
//Yaf_Route_Rewrite
//建立一个路由协议实例
$route = new Yaf_Route_Rewrite('product/:ident', //这儿能够是:也能够是*
array('controller' => 'products','action' => 'view')
);
//使用路由器装载路由协议
$router->addRoute('product', $route);
//控制器里用:$this->getRequest()->getParam('ident');
$route = new Yaf_Route_Regex(
'/([0-9]+)/',
array(
'module'=>'index',
'controller' => 'products',
'action' => 'show'
),
array("1"=>'pid')
);
$router->addRoute("name", $route);
以Yaf_Route_Simple为例
咱们在控制器index下新增
public function testAction() {//默认Action
$this->getView()->assign("content", "Hello Test");
}
访问http://127.0.01/?c=index&a=test M不写默认index
打印 Hello Test!
你也能够经过
print_r($this->getRequest());
打印出路由信息
Yaf_Request_Http Object | |
( | |
[module] => Index | |
[controller] => Index | |
[action] => test | |
[method] => GET | |
[params:protected] => Array | |
( | |
) | |
[language:protected] => | |
[_exception:protected] => | |
[_base_uri:protected] => | |
[uri:protected] => / | |
[dispatched:protected] => 1 | |
[routed:protected] => 1 | |
) |