【问题标题】:Expression Language in conditional routing - service in context条件路由中的表达式语言 - 上下文中的服务
【发布时间】:2015-09-04 12:59:50
【问题描述】:

根据docs,默认情况下只有两个可用的东西,而在条件路由中使用expression language - context 和request。

我想使用foo 服务和布尔bar() 方法来确定条件。如何在这种情况下注入foo 服务?

到目前为止我已经尝试过:

some_route:
    path: /xyz
    defaults: {_controller: "SomeController"}
    condition: "service('foo').bar()"

和

some_route:
    path: /xyz
    defaults: {_controller: "SomeController"}
    condition: "service('foo').bar() === true"

但我得到的只是:

The function "service" does not exist around position 1.

P.s.:我使用的是 Symfony 2.7。

【问题讨论】:

    标签: symfony routing


    【解决方案1】:

    最简单的方法是覆盖context 变量,您可以通过装饰router.request_context 服务来做到这一点。

    services.xml:

    <service id="router.request_context.decorated" class="Your\RequestContext" decorates="router.request_context" public="false">
            <argument>%router.request_context.base_url%</argument>
            <argument>GET</argument>
            <argument>%router.request_context.host%</argument>
            <argument>%router.request_context.scheme%</argument>
            <argument>%request_listener.http_port%</argument>
            <argument>%request_listener.https_port%</argument>
            <argument>/</argument>
            <argument type="string"/>
            <argument id="service_container" type="service"/>
    </service>
    

    RequestContext 类:

    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class RequestContext extends \Symfony\Component\Routing\RequestContext
    {
        /**
         * @var ContainerInterface
         */
        private $container;
    
        public function __construct($baseUrl = '', $method = 'GET', $host = 'localhost', $scheme = 'http', $httpPort = 80, $httpsPort = 443, $path = '/', $queryString = '', ContainerInterface $container)
        {
            parent::__construct($baseUrl, $method, $host, $scheme, $httpPort, $httpsPort, $path, $queryString);
            $this->container = $container;
        }
    
        /**
         * @return mixed
         */
        public function service($service)
        {
            return $this->container->get($service);
        }
    }
    

    routing.yml:

    some_route:
        path: /xyz
        defaults: {_controller: "SomeController"}
        condition: "context.service('foo').bar()"
    

    此外,您可以创建表达式语言提供程序并注册service 函数以简单地使用service('foo') 而不是context.service('foo') - 您需要在Symfony\Component\Routing\Router 类上添加运行addExpressionLanguageProvider 的此提供程序。

    容格汉斯! :)

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多