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

symfony路由组件(The Routing Component)

程序员文章站 2022-05-24 12:26:01
...
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 已经加载了这个组件:

useSymfony\Component\Routing\Matcher\UrlMatcher;
useSymfony\Component\Routing\RequestContext;
useSymfony\Component\Routing\RouteCollection;
useSymfony\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

以上就介绍了symfony路由组件(The Routing Component),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。