【问题标题】:symfony/Routing and request contextsymfony/路由和请求上下文
【发布时间】:2013-03-08 04:56:09
【问题描述】:

读symfony/路由readme

// ...

$context = new RequestContext();

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

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

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

编辑

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

【问题讨论】:

    标签: symfony routing


    【解决方案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']);
    

    【讨论】:

    • 但是这个对象是如何被 Matcher 使用的?
    • @spajak 匹配器可以根据请求上下文中包含的数据重新创建请求对象。此外,UrlGenerator 类可以使用此数据生成绝对请求路径。
    猜你喜欢
    • 2019-08-17
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多