Sebastien Hoek
Sebastien Hoek

Reputation: 63

Symfony SessionInterface as service the same as Request getSession()

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:

  1. Is this the/a correct way to work with sessions in Symfony?
  2. Is 'just_a_preference' saved in the same session parameter bag as my $request->getSession()?
  3. If not, what is the correct way to work with the current request session outside the controller?

If work with Symfony 4.4.

Upvotes: 2

Views: 729

Answers (1)

Mike Doe
Mike Doe

Reputation: 17624

  1. 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:

    1. extend the functionality: the service behind the interface can be easily decorated – eg. LoggingSessionDecorator which would log session activity
    2. proper OOP code: with $request->getSession()->set(…) you violate the Law of Demeter principle, that said:
    3. it's easier to mock the session in your unit tests
  2. In the end – yes, it doesn't matter. Both methods reference the same object

  3. As said in 1, better to use the interface. At least in my opinion.

Upvotes: 1

Related Questions