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 variables inside DI definition.

Hi,

I am wondering on how to access session variables inside FactoryDefault::setShared() or most commonly know as $di. I know we can access it using $_SESSION but is there any more Phalcon way of doing this?

Thanks!

Yes there is:

$di->get('session')->get('variablename')

Read docs next time.



3.3k

Thanks for your reply, but sadly, this won't work. $di is not accessible inside the said function. And yes, I do read the docs and search the Internet before I ask. ;)

Yes there is:

```php $di->get('session')->get('variablename') ```

Read docs next time.



3.3k

In case I wasn't clear enough:

$di->setShared('someName', function() {
    print_r($_SESSION);
});

What I was hoping to achieve is to access session variables without using $_SESSION from inside FactoryDefault::setShared(). I tried $di (instance of FactoryDefault()) and I have tried $application (instance of Application()) but both are not accesible from the definition.

I hope that makes it more clear. If it is still not, let me know. Thanks!

If you are using phalcon 2.1.x Then you can use:

$di->setShared('someName', function() {
    $session = $this->get('session');
});

Service closures are bound to DI in phalcon 2.1.x, in 2.0.x you need to use:

$di->setShared('someName', function() use ($di) {
    $session = $di->get('session');
});


50.6k
Accepted
answer

The DI can be accessed anywhere by doing:

$di = \Phalcon\DI::getDefault()

I've written a trait that I inject into any models or classes that don't have easier access to the DI:

/**
 * This trait contains a simple function for simplifying access to the DI.
 */
trait DI{
    /**
     * Shortcut function for accessing the DI and its contents
     * 
     * @param string $thing_in_di   [OPTIONAL]  If provided, causes the method to return that item in the DI, rather than the DI itself
     * @param array $parameters_for_thing [OPTIONAL] If provided, passes the parameters on to the closure method for creating the thing
     * @return DI|Service
     */
    public function di($thing_in_di=NULL,$parameters_for_thing=NULL){

        if($thing_in_di == NULL){
            return \Phalcon\DI::getDefault();
        }
        else{
            return \Phalcon\DI::getDefault()->get($thing_in_di,$parameters_for_thing);
        }
    }
}