How to inject the @request into a service?

后端 未结 9 2260
Happy的楠姐
Happy的楠姐 2020-12-01 05:53

When I try to inject the @request into any of my services, I get this exception:

ScopeWideningInjectionException: Scope Widening Injection detected:

9条回答
  •  盖世英雄少女心
    2020-12-01 06:24

    I think it's more important to focus on getting the request instead of setting it. I would do something similar to @Blowski's solution, except using a getter. This is very similar to the documentation's example.

    namespace Acme\HelloBundle\Newsletter;
    
    use Symfony\Component\HttpFoundation\RequestStack;
    
    class NewsletterManager
    {
        protected $requestStack;
    
        public function __construct(RequestStack $requestStack)
        {
            $this->requestStack = $requestStack;
        }
    
        protected function getRequest()
        {
            return $this->requestStack->getCurrentRequest();
        }
    
        public function foo()
        {
            $request = $this->getRequest();
            // Do something with the request
        }
    }
    

    And your services.yml config file.

    services:
        newsletter_manager:
            class:     Acme\HelloBundle\Newsletter\NewsletterManager
            arguments: ["@request_stack"]
    

    Now you're always sure that you're getting the correct request, and you don't have to worry about setting/re-setting the request.

提交回复
热议问题