Only start sessions on auth

According to the documentation, we use the DI in the middleware to create sessions. This results in empty sessions being created. Since i am creating an admin portal, I want to avoid empty sessions at all costs. I am using the database adapter and do not want empty sessions stored in the DB.

I would prefer to only start a session once a user is authenticated. What would be the best way to achieve this.

edited Jun '17

You can use This code inside Controller :

    $this->di->setShared('session', function () {

            $session = new SessionAdapter();


            return $session;

Don't forget to add :

use Phalcon\Session\Adapter\Files as SessionAdapter;

at top of class.

Simply do not call $session->start(); inside of session service definition.

Afterwards, when you validate user, get session service from DI and call start() method.

edited Jun '17

Be carreful $session->start(); does not just start the session

in next calls, it's also used to read cookies and retrieve if user is connected

but you can try to add it into the DI only in your admin controller and redirect to the login page if user not connected