Symfony路由条件DSL上下文

问题描述 投票:2回答:1

简短版本:在使用Symfony的路由条件时,最终用户程序员可以访问哪些对象?

长版本:Symfony路线允许您使用a key named condition

contact:
    path:       /contact
    controller: 'App\Controller\DefaultController::contact'
    condition:  "context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'"

condition的值是代码 - 它是基于(但不完全相同于)twig模板语言语法的Symfony域特定语言(DSL)。 Symfony docs refer to this as "The Expression Syntax"

我已经能够从文档中收集到这么多。我无法弄清楚我可以使用这个DSL访问什么对象?即在上面的例子中,表达式似乎可以访问context对象和request对象。

还有其他人吗?源代码中是否有文档或位置,我可以通过condition查看我可以访问的其他对象?

php symfony dsl symfony-routing
1个回答
1
投票

documentation you are linking声明表达式中只有这两个对象可用:

您可以通过利用传递到表达式中的两个变量来执行表达式中所需的任何复杂逻辑:

context - RequestContext的一个实例,它包含有关匹配路由的最基本信息。

请求 - Symfony Request对象(请参阅请求)。

(强调我的)。

您可以在Symfony\Component\Routing\Matcher\UrlMatcher::handleRouteRequirements()上查看这些对象注入表达式的位置:

protected function handleRouteRequirements($pathinfo, $name, Route $route)
{
    // expression condition
    if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
        return [self::REQUIREMENT_MISMATCH, null];
    }

    return [self::REQUIREMENT_MATCH, null];
}

evaluate()的调用既传递了你在condition键上定义的表达式,也传递了一个带有$context$request的数组。

© www.soinside.com 2019 - 2024. All rights reserved.