在說路由之前我們先看一張yaf的整體流程圖如下:

#### 簡單的理解
就我的理解來說,路由分發過程的執行動作是,獲取用戶請求的URl,根據路由規則解析這個URL,得到module、controller、action、param、query,根據獲得的module和controller去載入控制器,執行對應的action方法。
#### 插件鉤子
路由器也有插件鉤子,就是routerStartup和routerShutdown,他們在路由解析前后分別被調用.
### 設置路由的方法
#### 1、先添加配置
> routes.regex4.type="regex"
routes.regex4.match="#^/news/([^/]*)/([^/]*)#"
routes.regex4.route.controller=news
routes.regex4.route.action=detail
routes.regex4.map.1=id
routes.regex4.map.2=sort
#### 2、在Bootstap.php中添加路由配置
`<?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);
}
}`
#### 3、添加接收的控制器
`<?php
class NewsController extends Yaf_Controller_Abstract {
public function init()
{
Yaf_Dispatcher::getInstance()->disableView();
}
public function detailAction($id = 0,$sort = '')
{
print_r($this->getRequest()->getParams());
echo 'News Detail:'.$id.',sort:'.$sort;
}
}
?>`
#### 4、訪問url: yourhost/news/78/create_time
當訪問這個url,yaf先根據我們的路由規則解析出默認的module,news控制器,detailAction,第一個參數id,第二個參數,sort。
#### 我們來分析一下解析流程:
Yaf_Application::app()->bootstrap()->getDispatcher->dispatch();
1.在yaf_dispatcher_route中,完成路由解析,得到module='',controller=news,action=detail
2.在yaf_dispatcher_fix_default中,通過其處理得到module=index,controller=news,action=detail
3.在2中完成之后,通過如果有hook機制,就會執行插件鉤子:routerShutdown
4.在yaf_internal_autoload中完成自動加載類文件,application/controllers/News.php
5.執行detailAction
### 在Bootstrap.php中配置路由規則
上面就是一個簡單的通過正則的方式來設置路由的示例,我們還可以直接在Bootstrap.php添加我們的路由規則:
` public function _initRoute(Yaf_Dispatcher $dispatcher) {
$router = Yaf_Dispatcher::getInstance()->getRouter();
$router->addConfig(Yaf_Registry::get("config")->routes);
//在剛才的示例里添加上下面兩行
$route = new Yaf_Route_Simple("m", "c", "a");
$router->addRoute("simple", $route);
}`
#### 測試一下
我們就可以嘗試用 yourhost?c=news&a=detail 訪問你的newsController,detailAction了。
### Yaf_Route_Simple
上面是Yaf_Route_Simple的一個示例
Yaf_Route_Simple是基于請求中的query string來做路由的, 在初始化一個Yaf_Route_Simple路由協議的時候, 我們需要給出3個參數, 這3個參數分別代表在query string中Module, Controller, Action的變量名,它也可以直接在配置信息里設置
> routes.simple.type="simple"
routes.simple.controller=c
routes.simple.module=m
routes.simple.action=a
更多關于路由的信息可以參見官方文檔:http://www.laruence.com/manual/yaf.routes.static.html