学习yaf(四)路由

使用路由

使用路由既可以让之很复杂,同时也能让它很简单,这是归于你的应用。然而使用一个路由是很简单的,你可以添加你的路由协议给路由器,这样就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
  )
posted @ 2017-06-12 15:45  禾火意  阅读(1227)  评论(0编辑  收藏  举报