欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Zend Framework教程之路由功能Zend_Controller_Router详解

程序员文章站 2023-12-10 23:20:16
本文实例讲述了zend framework教程之路由功能zend_controller_router用法。分享给大家供大家参考,具体如下: zend framework的...

本文实例讲述了zend framework教程之路由功能zend_controller_router用法。分享给大家供大家参考,具体如下:

zend framework的路由提供了两个主要功能路由和创建路由。

zend_controller_router的route类和相应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);
}

zend_controller_router_abstract

<?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;
  }
}

zend_controller_router_rewrite

<?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;
  }
}

添加路由的操作方法

public function addroute($name, zend_controller_router_route_interface $route)
public function addroutes($routes)

$router = $ctrl->getrouter(); // returns a rewrite router by default
$router->addroute('user',
         new zend_controller_router_route('user/:username'));

addroute的第一个参数是路由名。第二个参数是路由自己。路由名最普通的用法是通过zend_view_url助手的方法:

"<?= $this->url(array('username' => 'martel'), 'user') ?>">martel</a>

它将导致在 href: user/martel.

路由是一个简单的过程,这个过程通过所有提供的路由和匹配它的当前请求的uri定义来迭代。当一个正匹配被发现,变量值从路由实例返回并注入到zend_controller_request对象以备将来在派遣器和用户创建的控制器中使用。如果是负匹配,在链中的下个路由被检查。

note: 倒序匹配

用倒序来匹配路由确保最通用的路由被首先定义。

note: 返回的值

从路由返回的值来自于url参数或用于定义的缺省值。这些变量以后可通过zend_controller_request::getparam() 或 zend_controller_action::_getparam() 方法来访问。

有三个特殊的变量可用于你的路由-'module'、 'controller' 和 'action'。这些特殊的变量被zend_controller_dispatcher用来找出控制器和动作然后派遣过去。

note: 特殊变量

如果你选择通过 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名(index)为'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。

note: 字符的的用法

当前的实现允许你使用任何字符(正斜杠除外)作为变量标识符,但强烈建议只使用php使用的变量标识符。将来的实现也许会改变这个行为,它可能会导致在你的代码里有隐藏的bugs。

当你把浏览器指向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的urls。对于后者变量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这样的url将不被匹配并且控制将被传递给在链中的下一个路由。

主机名路由

你也可以使用主机名做路由匹配。对简单的匹配使用静态主机名选项:

$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的url,并分派到 authcontroller::loginaction().

zend_controller_router_route_regex

除了缺省的和静态的路由类型外,正则表达式路由类型也可用。这个路由比其它路由更强更灵活,只是稍微有点复杂。同时,它应该比标准路由快。

象标准路由一样,这个路由必须用路由定义和一些缺省条件来初始化。让我们创建一个archive路由作为例子,和先前定义的类似,这次只是用了regex:

$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'
);

note: 在匹配之前,开头和结尾的斜杠从路由器里的url中去除掉了。结果,匹配http://domain.com/foo/bar/,需要foo/bar这样的regex,而不是/foo/bar。

note: 行开头和行结尾符号(分别为'^' 和 '$')被自动预先追加到所有表达式。这样,你不需要在你的正则表达式里用它们,你应该匹配整个字符串。

note: 这个路由类使用#符作为分隔符。这意味着你将需要避免哈希符('#')但不是正斜杠('/')在你的路由定义里。因为'#'符(名称为锚)很少被传给webserver,你将几乎不需要在你的regex里使用它。

你可以用通常的办法获得已定义的子模式的内容:

public function showaction()
{
  $request = $this->getrequest();
  $year  = $request->getparam(1); // $year = '2006';
}

note: 注意这个键是整数(1) 而不是字符串('1')。

因为'year'的缺省没有设置,这个路由将和它的标准路由副本不是非常精确地相同。即使我们为'year'声明一个缺省并使子模式可选,也不清楚是否会在拖尾斜杠(trailing slash)上还将有问题。方案是使整个'year'部分和斜杠一起可选但只抓取数字部分:(这段比较绕口,请校对者仔细看看,谢谢 jason qi)

$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)
);

note: 子模式键必须用整数表示。

注意在请求值中的数字索引不见了,代替的是一个名字变量。当然如果你愿意可以把数字和名字变量混合使用

$route = new zend_controller_router_route_regex(
  'archive/(\d+)/page/(\d+)',
  array( ... ),
  array('year' => 1)
);

这将导致在请求中有混合的值可用。例如:urlhttp://domain.com/archive/2006/page/10将在下列结果中:

$values = array(
  'year'    => '2006',
  2      => 10,
  'controller' => 'archive',
  'action'   => 'show'
);

因为regex模型不容易颠倒,如果你想用url助手或这个类中的 assemble方法,你需要准备一个颠倒的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这样的urls,还有把解析它路径元素中的最后部分,01-using_the_regex_router.html,到一个文章的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);

正如你所看到的,这个在标准路由上添加了巨大的灵活性。

通过配置文件定义路由规则

例如

[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);
}

路由只发生一次:当请求第一次接收到系统。路由器的意图是基于请求的环境决定控制器、动作和可选的参数,并把它们发给请求。请求对象接着传递给派遣器。如果不可能映射一个路由到一个派遣令牌,路由器对请求对象就什么也不做。

更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。