Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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!



5.1k

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



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

`



5.1k

Thanks for the great software and awesome support.



2.1k

thanks for this too



1.7k

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