Zend Framework路由功能概述
本示例深入解析Zend Framework中Zend_Controller_Router组件的路由用法,供开发者参考与实践。
Zend Framework的路由模块主要承担两项核心职责:匹配请求路径(路由)以及构建反向URL(创建路由)。
Zend_Controller_Router命名空间下的Route类及其子目录中的各类,封装了常见的路由操作逻辑。
Zend_Controller_Router_Interface接口、Zend_Controller_Router_Abstract抽象类以及Zend_Controller_Router_Rewrite具体类,共同构成了基础路由管理、路由注册与移除的核心架构。
└── Router ├── Abstract.php ├── Exception.php ├── Interface.php ├── Rewrite.php ├── Route │ ├── Abstract.php │ ├── Chain.php │ ├── Hostname.php │ ├── Interface.php │ ├── Module.php │ ├── Regex.php │ └── Static.php └── Route.php
Zend_Controller_Router路由功能的底层实现机制。
Zend_Controller_Router_Interface定义了路由器必须遵循的契约。
<?php
interface Zend_Controller_Router_Interface
{
/**
* Processes a request and sets its controller and action. If
* no route was possible, an exception is thrown.
*
* @param Zend_Controller_Request_Abstract
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Request_Abstract|boolean
*/
public function route(Zend_Controller_Request_Abstract $dispatcher);
/**
* Generates a URL path that can be used in URL creation, redirection, etc.
*
* May be passed user params to override ones from URI, Request or even defaults.
* If passed parameter has a value of null, it's URL variable will be reset to
* default.
*
* If null is passed as a route name assemble will use the current Route or 'default'
* if current is not yet set.
*
* Reset is used to signal that all parameters should be reset to it's defaults.
* Ignoring all URL specified values. User specified params still get precedence.
*
* Encode tells to url encode resulting path parts.
*
* @param array $userParams Options passed by a user used to override parameters
* @param mixed $name The name of a Route to use
* @param bool $reset Whether to reset to the route defaults ignoring URL params
* @param bool $encode Tells to encode URL parts on output
* @throws Zend_Controller_Router_Exception
* @return string Resulting URL path
*/
public function assemble($userParams, $name = null, $reset = false, $encode = true);
/**
* Retrieve Front Controller
*
* @return Zend_Controller_Front
*/
public function getFrontController();
/**
* Set Front Controller
*
* @param Zend_Controller_Front $controller
* @return Zend_Controller_Router_Interface
*/
public function setFrontController(Zend_Controller_Front $controller);
/**
* Add or modify a parameter with which to instantiate any helper objects
*
* @param string $name
* @param mixed $param
* @return Zend_Controller_Router_Interface
*/
public function setParam($name, $value);
/**
* Set an array of a parameters to pass to helper object constructors
*
* @param array $params
* @return Zend_Controller_Router_Interface
*/
public function setParams(array $params);
/**
* Retrieve a single parameter from the controller parameter stack
*
* @param string $name
* @return mixed
*/
public function getParam($name);
/**
* Retrieve the parameters to pass to helper object constructors
*
* @return array
*/
public function getParams();
/**
* Clear the controller parameter stack
*
* By default, clears all parameters. If a parameter name is given, clears
* only that parameter; if an array of parameter names is provided, clears
* each.
*
* @param null|string|array single key or array of keys for params to clear
* @return Zend_Controller_Router_Interface
*/
public function clearParams($name = null);
}
</code></pre>
Zend_Controller_Router_Abstract提供了路由管理的通用基础实现。
<pre class="brush:php;"><code class="language-php">
<?php
/** Zend_Controller_Router_Interface */
require_once 'Zend/Controller/Router/Interface.php';
abstract class Zend_Controller_Router_Abstract implements Zend_Controller_Router_Interface
{
/**
* URI delimiter
*/
const URI_DELIMITER = '/';
/**
* Front controller instance
* @var Zend_Controller_Front
*/
protected $_frontController;
/**
* Array of invocation parameters to use when instantiating action
* controllers
* @var array
*/
protected $_invokeParams = array();
/**
* Constructor
*
* @param array $params
* @return void
*/
public function __construct(array $params = array())
{
$this->setParams($params);
}
/**
* Add or modify a parameter to use when instantiating an action controller
*
* @param string $name
* @param mixed $value
* @return Zend_Controller_Router
*/
public function setParam($name, $value)
{
$name = (string) $name;
$this->_invokeParams[$name] = $value;
return $this;
}
/**
* Set parameters to pass to action controller constructors
*
* @param array $params
* @return Zend_Controller_Router
*/
public function setParams(array $params)
{
$this->_invokeParams = array_merge($this->_invokeParams, $params);
return $this;
}
/**
* Retrieve a single parameter from the controller parameter stack
*
* @param string $name
* @return mixed
*/
public function getParam($name)
{
if(isset($this->_invokeParams[$name])) {
return $this->_invokeParams[$name];
}
return null;
}
/**
* Retrieve action controller instantiation parameters
*
* @return array
*/
public function getParams()
{
return $this->_invokeParams;
}
/**
* Clear the controller parameter stack
*
* By default, clears all parameters. If a parameter name is given, clears
* only that parameter; if an array of parameter names is provided, clears
* each.
*
* @param null|string|array single key or array of keys for params to clear
* @return Zend_Controller_Router
*/
public function clearParams($name = null)
{
if (null === $name) {
$this->_invokeParams = array();
} elseif (is_string($name) && isset($this->_invokeParams[$name])) {
unset($this->_invokeParams[$name]);
} elseif (is_array($name)) {
foreach ($name as $key) {
if (is_string($key) && isset($this->_invokeParams[$key])) {
unset($this->_invokeParams[$key]);
}
}
}
return $this;
}
/**
* Retrieve Front Controller
*
* @return Zend_Controller_Front
*/
public function getFrontController()
{
// Used cache version if found
if (null !== $this->_frontController) {
return $this->_frontController;
}
require_once 'Zend/Controller/Front.php';
$this->_frontController = Zend_Controller_Front::getInstance();
return $this->_frontController;
}
/**
* Set Front Controller
*
* @param Zend_Controller_Front $controller
* @return Zend_Controller_Router_Interface
*/
public function setFrontController(Zend_Controller_Front $controller)
{
$this->_frontController = $controller;
return $this;
}
}
</code></pre>
Zend_Controller_Router_Rewrite是默认的Rewrite路由器实现。
<pre class="brush:php;"><code class="language-php">
<?php
/** Zend_Controller_Router_Abstract */
require_once 'Zend/Controller/Router/Abstract.php';
/** Zend_Controller_Router_Route */
require_once 'Zend/Controller/Router/Route.php';
class Zend_Controller_Router_Rewrite extends Zend_Controller_Router_Abstract
{
/**
* Whether or not to use default routes
*
* @var boolean
*/
protected $_useDefaultRoutes = true;
/**
* Array of routes to match against
*
* @var array
*/
protected $_routes = array();
/**
* Currently matched route
*
* @var Zend_Controller_Router_Route_Interface
*/
protected $_currentRoute = null;
/**
* Global parameters given to all routes
*
* @var array
*/
protected $_globalParams = array();
/**
* Separator to use with chain names
*
* @var string
*/
protected $_chainNameSeparator = '-';
/**
* Determines if request parameters should be used as global parameters
* inside this router.
*
* @var boolean
*/
protected $_useCurrentParamsAsGlobal = false;
/**
* Add default routes which are used to mimic basic router behaviour
*
* @return Zend_Controller_Router_Rewrite
*/
public function addDefaultRoutes()
{
if (!$this->hasRoute('default')) {
$dispatcher = $this->getFrontController()->getDispatcher();
$request = $this->getFrontController()->getRequest();
require_once 'Zend/Controller/Router/Route/Module.php';
$compat = new Zend_Controller_Router_Route_Module(array(), $dispatcher, $request);
$this->_routes = array('default' => $compat) + $this->_routes;
}
return $this;
}
/**
* Add route to the route chain
*
* If route contains method setRequest(), it is initialized with a request object
*
* @param string $name Name of the route
* @param Zend_Controller_Router_Route_Interface $route Instance of the route
* @return Zend_Controller_Router_Rewrite
*/
public function addRoute($name, Zend_Controller_Router_Route_Interface $route)
{
if (method_exists($route, 'setRequest')) {
$route->setRequest($this->getFrontController()->getRequest());
}
$this->_routes[$name] = $route;
return $this;
}
/**
* Add routes to the route chain
*
* @param array $routes Array of routes with names as keys and routes as values
* @return Zend_Controller_Router_Rewrite
*/
public function addRoutes($routes) {
foreach ($routes as $name => $route) {
$this->addRoute($name, $route);
}
return $this;
}
/**
* Create routes out of Zend_Config configuration
*
* Example INI:
* routes.archive.route = "archive/:year/*"
* routes.archive.defaults.controller = archive
* routes.archive.defaults.action = show
* routes.archive.defaults.year = 2000
* routes.archive.reqs.year = "\d+"
*
* routes.news.type = "Zend_Controller_Router_Route_Static"
* routes.news.route = "news"
* routes.news.defaults.controller = "news"
* routes.news.defaults.action = "list"
*
* And finally after you have created a Zend_Config with above ini:
* $router = new Zend_Controller_Router_Rewrite();
* $router->addConfig($config, 'routes');
*
* @param Zend_Config $config Configuration object
* @param string $section Name of the config section containing route's definitions
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Rewrite
*/
public function addConfig(Zend_Config $config, $section = null)
{
if ($section !== null) {
if ($config->{$section} === null) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("No route configuration in section '{$section}'");
}
$config = $config->{$section};
}
foreach ($config as $name => $info) {
$route = $this->_getRouteFromConfig($info);
if ($route instanceof Zend_Controller_Router_Route_Chain) {
if (!isset($info->chain)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("No chain defined");
}
if ($info->chain instanceof Zend_Config) {
$childRouteNames = $info->chain;
} else {
$childRouteNames = explode(',', $info->chain);
}
foreach ($childRouteNames as $childRouteName) {
$childRoute = $this->getRoute(trim($childRouteName));
$route->chain($childRoute);
}
$this->addRoute($name, $route);
} elseif (isset($info->chains) && $info->chains instanceof Zend_Config) {
$this->_addChainRoutesFromConfig($name, $route, $info->chains);
} else {
$this->addRoute($name, $route);
}
}
return $this;
}
/**
* Get a route frm a config instance
*
* @param Zend_Config $info
* @return Zend_Controller_Router_Route_Interface
*/
protected function _getRouteFromConfig(Zend_Config $info)
{
$class = (isset($info->type)) ? $info->type : 'Zend_Controller_Router_Route';
if (!class_exists($class)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($class);
}
$route = call_user_func(array($class, 'getInstance'), $info);
if (isset($info->abstract) && $info->abstract && method_exists($route, 'isAbstract')) {
$route->isAbstract(true);
}
return $route;
}
/**
* Add chain routes from a config route
*
* @param string $name
* @param Zend_Controller_Router_Route_Interface $route
* @param Zend_Config $childRoutesInfo
* @return void
*/
protected function _addChainRoutesFromConfig($name,
Zend_Controller_Router_Route_Interface $route,
Zend_Config $childRoutesInfo)
{
foreach ($childRoutesInfo as $childRouteName => $childRouteInfo) {
if (is_string($childRouteInfo)) {
$childRouteName = $childRouteInfo;
$childRoute = $this->getRoute($childRouteName);
} else {
$childRoute = $this->_getRouteFromConfig($childRouteInfo);
}
if ($route instanceof Zend_Controller_Router_Route_Chain) {
$chainRoute = clone $route;
$chainRoute->chain($childRoute);
} else {
$chainRoute = $route->chain($childRoute);
}
$chainName = $name . $this->_chainNameSeparator . $childRouteName;
if (isset($childRouteInfo->chains)) {
$this->_addChainRoutesFromConfig($chainName, $chainRoute, $childRouteInfo->chains);
} else {
$this->addRoute($chainName, $chainRoute);
}
}
}
/**
* Remove a route from the route chain
*
* @param string $name Name of the route
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Rewrite
*/
public function removeRoute($name)
{
if (!isset($this->_routes[$name])) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Route $name is not defined");
}
unset($this->_routes[$name]);
return $this;
}
/**
* Remove all standard default routes
*
* @param Zend_Controller_Router_Route_Interface Route
* @return Zend_Controller_Router_Rewrite
*/
public function removeDefaultRoutes()
{
$this->_useDefaultRoutes = false;
return $this;
}
/**
* Check if named route exists
*
* @param string $name Name of the route
* @return boolean
*/
public function hasRoute($name)
{
return isset($this->_routes[$name]);
}
/**
* Retrieve a named route
*
* @param string $name Name of the route
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getRoute($name)
{
if (!isset($this->_routes[$name])) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Route $name is not defined");
}
return $this->_routes[$name];
}
/**
* Retrieve a currently matched route
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getCurrentRoute()
{
if (!isset($this->_currentRoute)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Current route is not defined");
}
return $this->getRoute($this->_currentRoute);
}
/**
* Retrieve a name of currently matched route
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getCurrentRouteName()
{
if (!isset($this->_currentRoute)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Current route is not defined");
}
return $this->_currentRoute;
}
/**
* Retrieve an array of routes added to the route chain
*
* @return array All of the defined routes
*/
public function getRoutes()
{
return $this->_routes;
}
/**
* Find a matching route to the current PATH_INFO and inject
* returning values to the Request object.
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Request_Abstract Request object
*/
public function route(Zend_Controller_Request_Abstract $request)
{
if (!$request instanceof Zend_Controller_Request_Http) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Zend_Controller_Router_Rewrite requires a Zend_Controller_Request_Http-based request object');
}
if ($this->_useDefaultRoutes) {
$this->addDefaultRoutes();
}
// Find the matching route
$routeMatched = false;
foreach (array_reverse($this->_routes, true) as $name => $route) {
// TODO: Should be an interface method. Hack for 1.0 BC
if (method_exists($route, 'isAbstract') && $route->isAbstract()) {
continue;
}
// TODO: Should be an interface method. Hack for 1.0 BC
if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) {
$match = $request->getPathInfo();
} else {
$match = $request;
}
if ($params = $route->match($match)) {
$this->_setRequestParams($request, $params);
$this->_currentRoute = $name;
$routeMatched = true;
break;
}
}
if (!$routeMatched) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('No route matched the request', 404);
}
if($this->_useCurrentParamsAsGlobal) {
$params = $request->getParams();
foreach($params as $param => $value) {
$this->setGlobalParam($param, $value);
}
}
return $request;
}
protected function _setRequestParams($request, $params)
{
foreach ($params as $param => $value) {
$request->setParam($param, $value);
if ($param === $request->getModuleKey()) {
$request->setModuleName($value);
}
if ($param === $request->getControllerKey()) {
$request->setControllerName($value);
}
if ($param === $request->getActionKey()) {
$request->setActionName($value);
}
}
}
/**
* Generates a URL path that can be used in URL creation, redirection, etc.
*
* @param array $userParams Options passed by a user used to override parameters
* @param mixed $name The name of a Route to use
* @param bool $reset Whether to reset to the route defaults ignoring URL params
* @param bool $encode Tells to encode URL parts on output
* @throws Zend_Controller_Router_Exception
* @return string Resulting absolute URL path
*/
public function assemble($userParams, $name = null, $reset = false, $encode = true)
{
if (!is_array($userParams)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('userParams must be an array');
}
if ($name == null) {
try {
$name = $this->getCurrentRouteName();
} catch (Zend_Controller_Router_Exception $e) {
$name = 'default';
}
}
// Use UNION (+) in order to preserve numeric keys
$params = $userParams + $this->_globalParams;
$route = $this->getRoute($name);
$url = $route->assemble($params, $reset, $encode);
if (!preg_match('|^[a-z]+://|', $url)) {
$url = rtrim($this->getFrontController()->getBaseUrl(), self::URI_DELIMITER) . self::URI_DELIMITER . $url;
}
return $url;
}
/**
* Set a global parameter
*
* @param string $name
* @param mixed $value
* @return Zend_Controller_Router_Rewrite
*/
public function setGlobalParam($name, $value)
{
$this->_globalParams[$name] = $value;
return $this;
}
/**
* Set the separator to use with chain names
*
* @param string $separator The separator to use
* @return Zend_Controller_Router_Rewrite
*/
public function setChainNameSeparator($separator) {
$this->_chainNameSeparator = $separator;
return $this;
}
/**
* Get the separator to use for chain names
*
* @return string
*/
public function getChainNameSeparator() {
return $this->_chainNameSeparator;
}
/**
* Determines/returns whether to use the request parameters as global parameters.
*
* @param boolean|null $use
* Null/unset when you want to retrieve the current state.
* True when request parameters should be global, false otherwise
* @return boolean|Zend_Controller_Router_Rewrite
* Returns a boolean if first param isn't set, returns an
* instance of Zend_Controller_Router_Rewrite otherwise.
*
*/
public function useRequestParametersAsGlobal($use = null) {
if($use === null) {
return $this->_useCurrentParamsAsGlobal;
}
$this->_useCurrentParamsAsGlobal = (bool) $use;
return $this;
}
}
</code></pre>
向路由器注册新路由的操作方法。
public function addRoute($name, Zend_Controller_Router_Route_Interface $route)
public function addRoutes($routes)
<pre class="brush:php;"><code class="language-php">
$router = $ctrl->getRouter(); // returns a rewrite router by default
$router->addRoute('user',
new Zend_Controller_Router_Route('user/:username'));
</code></pre>
addRoute方法的第一个参数指定路由名称,第二个参数为路由实例对象。路由名称通常用于Zend_View_Url助手生成链接。
<pre class="brush:php;"><code class="language-php">
"<?= $this->url(array('username' => 'martel'), 'user') ?>">Martel
例如,调用该助手将生成href属性值为user/martel的链接。
路由匹配是一个迭代过程,路由器依次检查所有已注册的路由以匹配当前请求URI。一旦找到正匹配,便从路由实例提取变量值并注入Zend_Controller_Request对象,供派遣器和控制器后续使用。若未匹配,则继续检查链中的下一个路由。
注意:倒序匹配策略。
采用倒序匹配机制可确保最通用的路由优先被定义和尝试,避免特定路由被通用规则拦截。
注意:返回值机制。
路由返回的值源自URL参数或定义时的默认值。这些变量随后可通过Zend_Controller_Request::getParam()或Zend_Controller_Action::_getParam()方法获取。
存在三个特殊变量'module'、'controller'和'action',Zend_Controller_Dispatcher利用它们定位目标控制器和方法并进行派遣。
注意:特殊变量配置。
若通过setControllerKey和setActionKey方法修改默认键名,上述特殊变量的名称也会相应改变。
缺省路由配置。
Zend_Controller_Router_Rewrite 和缺省路由一起预先配置,它将以controller/action的形式匹配URIs。另外,模块名可以被指定作为第一个路径参数,允许这种module/controller/action形式的URIs。最后,它也将缺省地匹配任何另外的追加到URI的参数-controller/action/var1/value1/var2/value2。
以下是缺省路由匹配的一些典型示例。
// Assuming the following:
$ctrl->setControllerDirectory(
array(
'default' => '/path/to/default/controllers',
'news' => '/path/to/news/controllers',
'blog' => '/path/to/blog/controllers'
)
);
Module only:
http://example/news
module == news
Invalid module maps to controller name:
http://example/foo
controller == foo
Module + controller:
http://example/blog/archive
module == blog
controller == archive
Module + controller + action:
http://example/blog/archive/list
module == blog
controller == archive
action == list
Module + controller + action + params:
http://example/blog/archive/list/sort/alpha/date/desc
module == blog
controller == archive
action == list
sort == alpha
date == desc
缺省路由本质上是存储在RewriteRouter中名为'default'的Zend_Controller_Router_Route_Module实例,其创建方式大致如下。
$compat = new Zend_Controller_Router_Route_Module(array(),
$dispatcher,
$request);
$this->addRoute('default', $compat);
若需移除该缺省路由,可重写名为'default'的路由,或调用removeDefaultRoutes()彻底清除所有默认路由。
// Remove any default routes
$router->removeDefaultRoutes();
为提升灵活性并支持自定义路由类型,Zend_Controller_Router定义了Zend_Controller_Router_Route_Interface接口及Zend_Controller_Router_Route_Abstract抽象类,实现其方法即可快速定义新路由类型。
Zend_Controller_Router提供的路由类型概览。
Zend_Controller_Router默认包含以下路由类型。
Zend_Controller_Router_Route Zend_Controller_Router_Route_Static Zend_Controller_Router_Route_Regex Zend_Controller_Router_Route_Hostname Zend_Controller_Router_Route_Module Zend_Controller_Router_Route_Chain Zend_Controller_Router_Route
Zend_Controller_Router_Route为标准框架路由,兼顾易用性与灵活性。每个路由包含基本URL映射(静态部分与动态变量),支持默认初始化或按需定制。
假设应用需要展示作者信息页面,希望访问http://domain.com/author/martel显示名为'martel'的作者资料。实现此功能的路由配置如下。
$route = new Zend_Controller_Router_Route(
'author/:username',
array(
'controller' => 'profile',
'action' => 'userinfo'
)
);
$router->addRoute('user', $route);
在Zend_Controller_Router_Route构造函数中,第一个参数为路由定义字符串,用于匹配URL。定义由斜杠('/')分隔的静态部分(如author)和动态部分组成,动态部分即变量,以冒号前缀标记(如:username)。
注意:字符使用规范。
当前实现允许除正斜杠外的任意字符作为变量标识符,但强烈建议仅使用PHP合法的变量标识符。未来版本可能放宽限制,可能导致代码中出现隐蔽Bug。
当浏览器访问http://domain.com/author/martel时,路由匹配成功,所有变量被注入Zend_Controller_Request对象,并在ProfileController中可用。返回的变量表现为键值对数组。
$values = array(
'username' => 'martel',
'controller' => 'profile',
'action' => 'userinfo'
);
随后,Zend_Controller_Dispatcher_Standard将调用默认模块下ProfileController类的userinfoAction()方法。开发者可通过Zend_Controller_Action::_getParam()或Zend_Controller_Request::getParam()访问这些变量。
public function userinfoAction()
{
$request = $this->getRequest();
$username = $request->getParam('username');
$username = $this->_getParam('username');
}
路由定义还可包含通配符'*',用于捕获额外参数,行为类似模块路由(URI中定义的var=>value)。以下路由模拟了模块路由的行为。
$route = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array('module' => 'default')
);
$router->addRoute('default', $route);
注意:变量默认值设置。
Zend_Controller_Router_Route构造函数的第二个参数为关联数组,键为变量名,值为期望的默认值。
$route = new Zend_Controller_Router_Route(
'archive/:year',
array('year' => 2006)
);
$router->addRoute('archive', $route);
上述路由可匹配http://domain.com/archive/2005及http://example.com/archive。对于后者,year变量将使用初始默认值2006。
此例将向请求对象注入year变量。由于未定义控制器和动作参数,应用将派遣至Zend_Controller_Dispatcher_Abstract中定义的默认控制器和方法。为提高可用性,应显式指定控制器和动作作为默认值。
$route = new Zend_Controller_Router_Route(
'archive/:year',
array(
'year' => 2006,
'controller' => 'archive',
'action' => 'show'
)
);
$router->addRoute('archive', $route);
该路由配置将导致派遣至ArchiveController类的showAction()方法。
注意:变量请求约束。
当需要约束变量格式时,可向Zend_Controller_Router_Route构造函数传入第三个参数,定义为正则表达式。
$route = new Zend_Controller_Router_Route(
'archive/:year',
array(
'year' => 2006,
'controller' => 'archive',
'action' => 'show'
),
array('year' => '\d+')
);
$router->addRoute('archive', $route);
基于上述定义,路由器仅在year变量包含数字时匹配,如http://domain.com/archive/2345。若访问http://example.com/archive/test,则不匹配并将控制权传递给链中下一个路由。
主机名路由配置。
可使用主机名进行路由匹配。简单匹配可使用静态主机名选项。
$route = new Zend_Controller_Router_Route(
array(
'host' => 'blog.mysite.com',
'path' => 'archive'
),
array(
'module' => 'blog',
'controller' => 'archive',
'action' => 'index'
)
);
$router->addRoute('archive', $route);
若需在主机名中匹配参数,可使用regex选项。示例中,子域作为用户名参数传递。组装路由时,可像其他路径参数一样传入用户名。
$route = new Zend_Controller_Router_Route(
array(
'host' => array(
'regex' => '([a-z]+).mysite.com',
'reverse' => '%s.mysite.com'
'params' => array(
1 => 'username'
)
),
'path' => ''
),
array(
'module' => 'users',
'controller' => 'profile',
'action' => 'index'
)
);
$router->addRoute('profile', $route);
Zend_Controller_Router_Route_Static用于固定路由。
配置固定不变的路由规则。
$route = new Zend_Controller_Router_Route_Static(
'login',
array('controller' => 'auth', 'action' => 'login')
);
$router->addRoute('login', $route);
上述路由将匹配http://domain.com/login,并分派至AuthController::loginAction()。
Zend_Controller_Router_Route_Regex提供正则表达式路由。
除标准路由外,正则表达式路由提供更强的灵活性和性能,尽管配置稍复杂。
与标准路由类似,需通过路由定义和默认条件初始化。以下示例使用Regex创建archive路由。
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)',
array(
'controller' => 'archive',
'action' => 'show'
)
);
$router->addRoute('archive', $route);
每个定义的regex子模式将被注入请求对象。成功匹配http://domain.com/archive/2006后,结果值数组如下。
$values = array(
1 => '2006',
'controller' => 'archive',
'action' => 'show'
);
注意:匹配前,路由器会自动去除URL首尾斜杠。因此,匹配http://domain.com/foo/bar/需使用foo/bar的正则,而非/foo/bar。
注意:行开头('^')和结尾('$')符号自动追加至所有表达式。无需手动添加,应匹配完整字符串。
注意:该路由类使用'#'作为分隔符。因此,路由定义中应避免使用哈希符('#'),但不影响正斜杠('/')。由于'#'极少传至Web服务器,通常无需在regex中使用它。
可通过常规方式获取已定义子模式的内容。
public function showAction()
{
$request = $this->getRequest();
$year = $request->getParam(1); // $year = '2006';
}
注意:键为整数(1)而非字符串('1')。
若未设置'year'默认值,该路由与标准副本不完全一致。即使声明默认值并使子模式可选,尾部斜杠仍可能引发问题。解决方案是将整个'year'部分及斜杠设为可选,但仅捕获数字部分。
$route = new Zend_Controller_Router_Route_Regex(
'archive(?:/(\d+))?',
array(
1 => '2006',
'controller' => 'archive',
'action' => 'show'
)
);
$router->addRoute('archive', $route);
使用整数键管理参数并非最佳实践,未来可能存在问题。因此引入第三个参数:联合数组,用于映射regex子模式索引到参数名。
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)',
array(
'controller' => 'archive',
'action' => 'show'
),
array(
1 => 'year'
)
);
$router->addRoute('archive', $route);
这将导致以下值被注入请求对象。
$values = array(
'year' => '2006',
'controller' => 'archive',
'action' => 'show'
);
映射可在任何目录下定义,使其适用于各种环境。键可包含变量名或子模式索引。
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)',
array( ... ),
array(1 => 'year')
);
// OR
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)',
array( ... ),
array('year' => 1)
);
注意:子模式键必须用整数表示。
注意:请求值中的数字索引消失,替换为命名变量。当然,也可混合使用数字和命名变量。
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)/page/(\d+)',
array( ... ),
array('year' => 1)
);
这将导致请求中包含混合类型的可用值。例如,URL http://domain.com/archive/2006/page/10将产生如下结果。
$values = array(
'year' => '2006',
2 => 10,
'controller' => 'archive',
'action' => 'show'
);
由于regex模型难以逆向,若需使用URL助手或assemble方法生成URL,需准备一个反向URL。反向路径由sprintf()可解析的字符串表示,并作为第四个构造参数定义。
$route = new Zend_Controller_Router_Route_Regex(
'archive/(\d+)',
array( ... ),
array('year' => 1),
'archive/%s'
);
虽然标准路由对象也能完成大部分工作,但Regex路由的优势在于能无限制地描述任意URL结构。例如,博客希望创建如http://domain.com/blog/archive/01-Using_the_Regex_Router.html的URL,并将最后部分解析为文章ID和标题/描述,这是标准路由无法做到的。使用Regex路由可实现如下方案。
$route = new Zend_Controller_Router_Route_Regex(
'blog/archive/(\d+)-(.+)\.html',
array(
'controller' => 'blog',
'action' => 'view'
),
array(
1 => 'id',
2 => 'description'
),
'blog/archive/%d-%s.html'
);
$router->addRoute('blogArchive', $route);
由此可见,Regex路由在标准路由基础上增添了巨大的灵活性。
通过配置文件定义路由规则。
例如INI文件配置。
[production]
routes.archive.route = "archive/:year/*"
routes.archive.defaults.controller = archive
routes.archive.defaults.action = show
routes.archive.defaults.year = 2000
routes.archive.reqs.year = "\d+"
routes.news.type = "Zend_Controller_Router_Route_Static"
routes.news.route = "news"
routes.news.defaults.controller = "news"
routes.news.defaults.action = "list"
routes.archive.type = "Zend_Controller_Router_Route_Regex"
routes.archive.route = "archive/(\d+)"
routes.archive.defaults.controller = "archive"
routes.archive.defaults.action = "show"
routes.archive.map.1 = "year"
; OR: routes.archive.map.year = 1
上述INI文件可被读取并加载至Zend_Config对象。
$config = new Zend_Config_Ini('/path/to/config.ini', 'production');
$router = new Zend_Controller_Router_Rewrite();
$router->addConfig($config, 'routes');
示例中,告知路由器使用INI文件中'routes'节的路由配置。该节下的顶级键用作路由名,定义了'archive'和'news'路由。每个路由至少需要一个'route'条目和一个或多个'defaults'条目;可选地,可指定'reqs'(required简写)。这三者对应Zend_Controller_Router_Route_Interface对象的三个参数。'type'选项用于指定路由类类型,默认为Zend_Controller_Router_Route。示例中,'news'路由被定义为使用Zend_Controller_Router_Route_Static。
自定义路由类型开发。
标准的Rewrite路由器应能满足大多数需求;多数情况下,只需创建新的路由类型即可扩展或修改功能。
若需不同的路由范式,接口Zend_Controller_Router_Interface提供了创建路由器所需的最少信息,仅包含单个方法。
interface Zend_Controller_Router_Interface
{
/**
* @param Zend_Controller_Request_Abstract $request
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Request_Abstract
*/
public function route(Zend_Controller_Request_Abstract $request);
}
路由仅在请求首次到达系统时执行一次。路由器的目的是基于请求环境确定控制器、动作及可选参数,并将其发送给请求对象。随后请求对象传递给派遣器。若无法将路由映射到派遣令牌,路由器将对请求对象不做任何操作。
希望本文所述内容能对PHP程序设计有所帮助。