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

Service access in Volt

Hey guys!

It's work:

{{ user.first_name }}

It's not work:

    {% if user %}
        Hello, {{user.first_name}}!
    {% else %}
        U a Guest!
    {%endif%}

User Service:

$di->set('user', function () use ($di){
    $sess = $di->get('session');
    if($sess->has('user')) {
        return $sess->get('user');
    } else return false;
});

Why second variant not working?

edited May '17

I don't think that you should save user as service in di. Why - because most likely phalcon uses isset/empty, and injectable class doesn't implement __isset magic method. This is why this not work and you shouldn't use it like this, use view paramter.

Wojciech, may be u right..

If you really want user in service, I would have a flag (property) in user for the state. And check like {% if user.isLogged is defined %} or something similar.

Nikolay, i use it solution, and it work for me:

$di->set("view", function () use($di){

    $view = new Phalcon\Mvc\View();
    ...
    $sess = $di->get('session');
    $user = $sess->has('user') ? $sess->get('user') : false;
    $view->setVar('user', $user);
    ...

});

спасиб за попытку помочь.



13.8k
edited May '17

In services.php you create a session service, which you can use to create and read sessions throughout your application. Setting session variables can be done in controllers and if you want to access the variable in the main theme you could use a Controller base to extend from. Below is how i solved it in my authentication i hope this helps

// start a session service in services.php

$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();

    return $session;
});
// store information in a session, for example if a user logged in

$this->session->set('auth-identity', [
          'id' => $user->id,
           'username' => $user->name,
           'image' => $user->image
]);
// Set the session variables in a view via a controller

$this->view->setVar('uid', $this->session->get('auth-identity')['id']);

// or if you want to access it in the main layout create a ControllerBase

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{

    public function onConstruct()
    {

        $this->view->setVar('uid', $this->session->get('auth-identity')['id']);
        $this->view->setVar('userName', $this->session->get('auth-identity')['username']);
        $this->view->setVar('userImage', $this->session->get('auth-identity')['image']);

    }

}
// And extend the other controllers  where you want to access the session variables from it like 

class YourController extends ControllerBase
{
    // your controller actions
}

Videles, thanks for a examples