1. 程式人生 > >學習yaf(四)路由

學習yaf(四)路由

protect 根據 route 構造 bar mod enc ble function

使用路由

使用路由既可以讓之很復雜,同時也能讓它很簡單,這是歸於你的應用。然而使用一個路由是很簡單的,你可以添加你的路由協議給路由器,這樣就OK了! 不同的路由協議如下所示:

Yaf_Route_Simple

Yaf_Route_Supervar

Yaf_Route_Static

Yaf_Route_Map

Yaf_Route_Rewrite

Yaf_Route_Regex

我們這裏就寫個簡單的幾個路由協議得demo

首先在配置文件中添加

;自定義路由
;順序很重要
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=page

;添加一個名為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
)

學習yaf(四)路由