2

The Drupal documentation on sessions mentions that sessions can be accessed via the Request object:

Session data is accessed via the \Symfony\Component\HttpFoundation\Request::getSession() method, which returns an instance of \Symfony\Component\HttpFoundation\Session\SessionInterface. The most important methods on SessionInterface are set(), get(), and remove().

However I've also dicovered there is a session service.

In a class where I need to use dependency injection and I do not by default have access to the Request object, do I still need to access the session via the request, or can I use it directy? Loading the Request instead and then accessing the session feels like adding overhead.

I have tried below code, which seems to be working fine. So then why do most examples and even the documentation still demonstrate the Request way? Am I missing something, or is there a risk in this approach?

class MyForm extends FormBase {

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\Session
   */
  protected $session;

  /**
   *
   * @param \Symfony\Component\HttpFoundation\Session\Session $session
   *   The session.
   */
  public function __construct($session) {
    $this->session = $session;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('session')
    );
  }

  function somefunction() {
    $this->session->get('value');
    $this->session->set('value', 'somevalue');
  }

}

1 Answer 1

0

... is there a risk in this approach?

If you have multiple requests you could get the wrong session object. Drupal moved a lot of things out of the request object, like routing and even the path info, but they didn't implemented a stacked session service and instead kept the session object in the request stack.

If you want to inject this service there is already a property in FormBase with getter and setter methods.

This works injected or not (see the comments at the top of the class):

$session = $this->getRequest()->getSession();
2
  • Thanks, I was not aware that the Form already had a method to access the request; that is obviously the cleanest way. I still don't fully get how there can be more sessions for a single user, I'd say that all requests are part of the same session. I can, however, understand that second tabs and AJAX requests might alter the contents of the session. Oct 25, 2021 at 10:44
  • 1
    For example in a test you could mock a session or another module could run your form in a sub-request with a different session than the main request.
    – 4uk4
    Oct 25, 2021 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.