条件路由中的表达语言-上下文中的服务 [英] Expression Language in conditional routing - service in context
问题描述
根据文档,只有两个在条件路由中使用表达式语言
时默认可用的东西-上下文
和请求
。
According to docs, there are only two things available by default, while using expression language
in conditional routes - context
and request
.
我想将 foo
服务与布尔值 bar()$ c一起使用$ c>确定条件的方法。如何在这种情况下注入
foo
服务?
I would like to use foo
service with boolean bar()
method to determine condition. How to inject foo
service into this condition?
到目前为止,我已经尝试过:
So far I've tried:
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.
Ps:我正在使用Symfony 2.7。
P.s.: I'm using Symfony 2.7.
推荐答案
最简单的方法是覆盖 context
变量,可以通过装饰 router.request_context
服务来实现。
Easiest way is to override context
variable, you can do that by decorating router.request_context
service.
services.xml:
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类:
RequestContext class:
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:
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
的此提供程序。 code>类。
Additionally, you can create expression language provider and register service
function to simply use service('foo')
instead of context.service('foo')
- you need to add this provider running addExpressionLanguageProvider
on Symfony\Component\Routing\Router
class.
Junger Hans! :)
Junger Hans! :)
这篇关于条件路由中的表达语言-上下文中的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!