When I try to inject the @request into any of my services, I get this exception:
ScopeWideningInjectionException: Scope Widening Injection detected:
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.