使用路由既可以让之很复杂,同时也能让它很简单,这是归于你的应用。然而使用一个路由是很简单的,你可以添加你的路由协议给路由器,这样就OK了! 不同的路由协议如下所示:
Yaf_Route_Simple |
Yaf_Route_Supervar |
Yaf_Route_Static |
Yaf_Route_Map |
Yaf_Route_Rewrite |
Yaf_Route_Regex |
首先让我们来看看路由器是如何让路由协议与之一起工作的. 在我们添加任何路由协议之前我们必须要得到一个路由器(Yaf_Router)实例, 我们通过派遣器的getRouter方法来得到默认的路由器:
一旦我们有了路由器实例,我们就能通过它来添加我们自定义的一些路由协议:
<?php
$router->addRoute('myRoute', $route);
$router->addRoute('myRoute1',$route)
除此之外,我们还可以直接添加在配置中定义我们路由协议:
例 8.2. 配置添加路由协议的例子
[common]
;自定义路由
;顺序很重要
routes.regex.type="regex"
routes.regex.match="#^/list/([^/]*)/([^/]*)#"
routes.regex.route.controller=Index
routes.regex.route.action=action
routes.regex.map.1=name
routes.regex.map.2=value
;添加一个名为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"
![]() |
注意 |
|---|---|
| 路由协议的顺序很重要, 所以Yaf保证添加顺序和在配置文件中的顺序相同 |
例 8.3. 然后在Bootstrap中通过调用Yaf_Router::addConfig添加定义在配置中的路由协议
<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initRoute(Yaf_Dispatcher $dispatcher) {
$router = Yaf_Dispatcher::getInstance()->getRouter();
/**
* 添加配置中的路由
*/
$router->addConfig(Yaf_Registry::get("config")->routes);
}
}
//其实路由器也提供给我们不同的方法来得到和设置包含在它内部的信息,一些重要的方法如下:
getCurrentRoute() //在路由结束以后, 获取起作用的路由协议
getRoute(), getRoutes();//看函数基本意思也就知道.