How to access cookies or request from a service? symfony
Question
I have a service, which requires to get some information from the request.
I do not want to pass those values to the service all the time, so is it possible, that the service gets some information about the request and especially the cookies by himself?
class SomeService {
public function someMethod() {
// access request and cookies, whithout passing in those values
}
}
Solution
inject the request
service then.
You surely have a service definition, modify it like this:
<service id="my_service" class="SomeService" scope="request">
<argument type="service" id="request" />
</service>
Then in your class, create a __construct method that will receive the request object:
class SomeService
{
private $request;
public function __construct(Request $request) {
$this->request = $request;
}
public function someMethod() {
$this->request->getSession();
}
}
OTHER TIPS
Alternatively, starting from Symfony 2.4, you can easily inject the new @request_stack
service.
From the docs:
If you are trying to inject the request service, the simple solution is to inject the
request_stack
service instead and access the current Request by calling thegetCurrentRequest()
method (see Injecting the Request)...
That should cover most cases.
@request_stack
emulates a @request
service that behaves like any other services in the app.
@request
is a special service because it may need to be instantiated several times (in sub-requests typically).
More info on that: Why not Inject the request Service?