symfony路由组件(The Routing Component)

来源:互联网 发布:淘宝一元拍卖的玉真假 编辑:程序博客网 时间:2024/05/20 04:46

The Routing component 把HTTP request转换为一系列的配置参数.

安装

你有两种方式来安装这个组件:

通过 Composer (symfony/routing on Packagist);使用官方的 Git repository (https://github.com/symfony/Routing)。

然后, 需要Composer把vendor/autoload.php 这个文件提供 给 autoloading mechanism 。 否则,你的应用程序将找不到这个组件。

用法

你需要下面三部分来设置基本的路由系统:

  • RouteCollection, 包含路由的定义(instances of the class Route)
  • RequestContext, 有关request的信息;
  • UrlMatcher, 把request匹配成单一的route(即确定需要使用那个route)

下面有个简单的例子。这里你需要确定你的autoloader 已经加载了这个组件:

use Symfony\Component\Routing\Matcher\UrlMatcher;use Symfony\Component\Routing\RequestContext;use Symfony\Component\Routing\RouteCollection;use Symfony\Component\Routing\Route;$route = new Route('/foo', array('controller' => 'MyController'));$routes = new RouteCollection();$routes->add('route_name', $route);$context = new RequestContext($_SERVER['REQUEST_URI']);$matcher = new UrlMatcher($routes, $context);$parameters = $matcher->match('/foo');// array('controller' => 'MyController', '_route' => 'route_name')

需要注意的是当使用$_SERVER[‘REQUEST_URI’]时,在URL上面可以包含任何参数。一个简单的解决办法就是使用HttpFoundation component 这个组件,下文将会解释这个组件。

未完待续

原文链接:
http://symfony.com/doc/current/components/routing/introduction.html

0 0