2

阅读 symfony/路由自述文件

// ...

$context = new RequestContext();

// this is optional and can be done without a Request instance
$context->fromRequest(Request::createFromGlobals());

$matcher = new UrlMatcher($routes, $context);

它是可选的是什么意思?没有它,Matcher 功能会受到某种限制吗?匹配器如何使用请求对象?

编辑

我发现 RouteListener 负责使用当前请求信息(主机、方法等)更新上下文。因此,当通过事件调度程序完成路由匹配时,不需要此可选步骤。

4

1 回答 1

1

创建新的RequestContext时,构造函数采用以下参数,如果您不这样做,则使用以下默认值。

$baseUrl   = ''
$method    = 'GET'
$host      = 'localhost'
$scheme    = 'http'
$httpPort  = 80
$httpsPort = 443
$path      = '/'

但是,RequestContext 对象可以从 HttpFoundation\Request 对象中检索这些值(如果已给出)。我相信这是 2.1 的新功能,因为 2.0 API 文档中没有提到它

您可以从自定义请求对象生成自己的上下文,而不是使用从 PHP Globals 创建的对象

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\HttpFoundation\Request;

$context = new RequestContext();

$context->fromRequest(Request::create('?foo=1&bar=2'));
$matcher = new UrlMatcher($routes, $context);

或直接应用 PHP Global 而无需创建新的 Request 对象

$context = new RequestContext($_SERVER['REQUEST_URI']);
于 2013-03-19T13:43:46.427 回答