Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set session variables for all the controllers in Symfony2?

Tags:

symfony

How do I create and access Symfony 2 session variables in my controllers. I used like this.

$session = new Session();
$session->start();
$session->set('loginUserId',$user['user_id']);

I want to know how to use the above session variable in all my controllers to access.

like image 710
Joe John Avatar asked Sep 05 '14 09:09

Joe John


People also ask

Can you change session variables?

Session variables on the client are read-only. They cannot be modified.


2 Answers

One way of using Sessions in Symfony in controller is:

setting:

$this->get('session')->set('loginUserId', $user['user_id']);

getting:

$this->get('session')->get('loginUserId');

If you use standard framework edition

like image 63
Gabriel Filipiak Avatar answered Nov 03 '22 09:11

Gabriel Filipiak


From the docs:

Symfony sessions are designed to replace several native PHP functions. Applications should avoid using session_start(), session_regenerate_id(), session_id(), session_name(), and session_destroy() and instead use the APIs in the following section.

and:

While it is recommended to explicitly start a session, a sessions will actually start on demand, that is, if any session request is made to read/write session data.

So sessions is started automatically and can be accessed e.g. from controllers via:

public function indexAction(Request $request)
{
    $session = $request->getSession();
    ...
}

or:

public function indexAction()
{
    $session = $this->getRequest()->getSession();
    // or
    $session = $this->get('session');
    ...
}

than:

// store an attribute for reuse during a later user request
$session->set('foo', 'bar');

// get the attribute set by another controller in another request
$foobar = $session->get('foobar');

// use a default value if the attribute doesn't exist
$filters = $session->get('filters', array());
like image 29
Kamil Adryjanek Avatar answered Nov 03 '22 09:11

Kamil Adryjanek