Reputation: 63
Symfony's SessionInterface is still a little bit vague / magic for me. So if someone can enlighten me, please.
Naturally, the request contains a session object and can be used within a controller.
class SimpleController extends AbstractController
{
public function index(Request $request): Response
{
$request->getSession()->set('session-var', 10);
}
}
However, within a service you can also include the SessionInterface as a service and work with, presumably, the same ParameterBag.
class SimpleService
{
public function __construct(SessionInterface $session)
{
$session->set('session-var', 10);
}
}
My colleague pointed out that a session is (and should always be) part of the request. This makes sense to me, but also got me thinking: why are you able to us the SessionInterface as a service when it is a object/property of the request.
What I want to achieve in the end is to include a service in my controller and in this service work with the current session.
Code example of my use case would look something like this.
class SimpleController extends AbstractController
{
private $simpleService;
public function __construct(SimpleService $simpleService)
{
$this->simpleService = $simpleService;
}
public function index(Request $request): Response
{
$this->simpleService->doSomething();
}
}
class SimpleService
{
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function doSomething()
{
// Do some things..... and save the result in the session.
$this->session->set('just_a_preference', 50);
}
}
So:
If work with Symfony 4.4.
Upvotes: 2
Views: 729
Reputation: 17624
Both methods are fine. They both reference the same object. Accessing the session via the interface is preferred though. I can come up with at least three reasons why:
LoggingSessionDecorator
which would log session activity$request->getSession()->set(…)
you violate the Law of Demeter principle, that said:In the end – yes, it doesn't matter. Both methods reference the same object
Upvotes: 1