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');
}
}