Symfony2 在服务中注入Request

Uncaught exception 
'Symfony\Component\DependencyInjection\Exception\ScopeWideningInjectionException'
 with message 'Scope Widening Injection detected: The definition 
"user.registration_initilize" references the service "request" which 
belongs to a narrower scope. Generally, it is safer to either move 
"mc_user.registration_initilize" to scope "request" or alternatively 
rely on the provider pattern by injecting the container itself, and 
requesting the service "request" each time it is needed.

当servive arguments 为[@request]时候出现这个报错

在symfony2中Service分两种 一个container 一个prototype 。

container是保存一个实例供多次使用

prototype是每次使用都会生成一个新的实例

这两者加入service参数是没问题的

但是 对于request每个子请求(subrequest)都会生成新的实例 跟前面两者又不一样

这里要把[@request] 换成 [@request_stack]

request_stack 即$this->getCurrentRequest()

这时候就在service中能获取当前的请求参数或者session了

作者:mot原文地址:https://segmentfault.com/a/1190000000474632

%s 个评论

要回复文章请先登录注册