Zend Framework自定义路由一则
2009年02月22日
by 庆亮
0 comments
经常性的看到如下的url:
http://www.example.com/id/4
或者更干脆
http://www.example.com/3
链接清爽,且搜索引擎友好.
ZF为我们提供了快速简单的实现方式,代码如下
//$front为前段控制器实例
$router = $front->getRouter();
//实现如http://www.example.com/id/4类型的url
$router->addRoute(
‘test1′,
new Zend_Controller_Router_Route(
‘id/:aid’,
array(‘controller’ => ‘index’ , ‘action’ => ‘view’)
))
//实现如http://www.example.com/3类型的url
->addRoute(
‘test2′,
new Zend_Controller_Router_Route(
‘/:aid’,
array(‘controller’ => ‘index’ , ‘action’ => ‘view’)
)
);
addRoute有两个参数,第一个为URL规则名称,第二个为URL规则的实例,该实例对应类必须实现Zend_Controller_Router_Interface接口,通常为Zend_Controller_Router_Route.
Zend_Controller_Router_Route有三个参数,定义原型为:
public function __construct($route, $defaults = array(), $reqs = array())
其中,
$route为URL匹配的方式, 例如test1实例中的’id/:aid’表示匹配http://www.example.com/id/x,":"代表之后为URL变量分隔符, 表示在实际的URL中aic为变量.
$defaults表示在URL匹配$route指定的形式时默认的各种参数,本例中设置了 控制器为index,动作为view, 所以当URL匹配时则相当于访问了http://www.example.com/index/view/id/x
$reqs则用于指定匹配的正则表达式, 例如 我们可以指定aid为整数时才匹配, 则:
$router->addRoute(‘test1′,
new Zend_Controller_Router_Route(‘id/:aid’,
array(
‘controller’=>‘index’,
‘action’=>‘view’
)
),
array(‘aid’=>‘\d+’)
);
简单的介绍下,更多请查看ZF手册.
补充:
定义了’id/:aid’形式的路由规则之后,在动作控制器中,使用
$this->_request->getParam(‘aid’);
来获得id值.