We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Accessing Session inside models

Hi,

With Controllers, we can use $this->session to access the session object.

But what is the recommended way to access session variables inside a model?

Regards!



7.3k

Also, if I have a general class (not a model), what is the best practice to access session variable inside it?



98.9k
Accepted
answer

Hi, you can use the DI to access services inside a model:

<?php
class Robots extends Phalcon\Mvc\Model
{
   public function beforeCreate()
   {
      $this->userId = $this->getDI()->getSession()->get('user-id');
   }
}


7.3k

Thanks for the great software and awesome support.



4.5k

thanks for this too



4.2k

Hi, I'm new on the forum and using Phalcon (great) I use "$this->getDI()->getSession()" to have some variables in my Model Class but I have this message: Notice: A session had already been started - ignoring session_start() As it's a notice I guess it's not a big issue, but is there anyway to access session data without trying to start a new session Thanks

edited Oct '14

hi "cmeheut", you can use create SESSION code

$di->setShared('session', function () {//Use setShared
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});