DavidW
DavidW

Reputation: 5129

Auto starting session in Symfony2

It seems Symfony 2.1 does not auto start sessions. Is there a way for me to auto start them?

I have an application that requires user's session id in several actions, but there is no way to know which one will need it first, so I can not start it on demand, I need it to be there when I request it.

Upvotes: 2

Views: 4413

Answers (2)

John Cartwright
John Cartwright

Reputation: 5084

You can tell the framework session configuration (defined in your config.xml) to auto start the session.

However, this is depecated. Sessions by design are started on demand.

<framework:config>
    <framework:session auto-start="true"/>
</framework:config>

My question would be why would you want to initialize a session unless you're using it?

Upvotes: 1

Wilq
Wilq

Reputation: 2272

As I understand, you need user's session id in some place from already started session, and if there is no session started yet, you want to do it

In this case try:

use Symfony\Component\HttpFoundation\Session\Session; // use sessions

class yourController extends Controller
{
    public function yourAction()
    { 

        $session = $this->getRequest()->getSession(); // Get started session
        if(!$session instanceof Session)
            $session = new Session(); // if there is no session, start it

        $value = $session->getId(); // get session id


        return $this->render('YourSampleBundle:your:your.html.twig',array(
                'session_id' => $value
        ));
    }

}

Upvotes: 1

Related Questions