简体   繁体   中英

Phalcon php undefined variable session

I am studying Phalcon and I'm trying to set username to session OOP Phalcon style. Here is what I have in my controller:

$users = Users::find(array($conditions, 'bind' => $parameters));
            if (count($users) > 0) {
                //login
                $this->session->start();
                $this->session->set("username", $username);
                $this->view->successMessage = "You are logged in";

            }

This is a chunk of loginAction. If I print_r($_SESSION); in login.volt (where user gets redirected after login action) it prints out the session, but in other views when I try to print session I get an error: undefined variable session. In my services.php I have

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

Would be grateful for any help

EDIT Let me put it this way. In normal php I could do something like this: username; ?>

And then in view I could do something like:

 <?php 
        if (isset($_SESSION['username']))  
             {  
                echo '<input type="submit" name="Button" value="button"'; 
             }
 ?>

What is the equivalent in Phalcon?

When you retrieve your shared service via DI::getShared('session') (in your case in controller via $this->session ) it will start the session for you, so no need to manually start it again. Here in documentation is pretty much how you should do it.

Another point, it would make the most sense to use session bag or persistent storage , second use the same implementation as session bags but kind of a shortcut.

And actually, not less of a valid point about retrieving session data in your views – you should pass it as a view variable, not implement that logic in the view (if you want more of a proper Phalcon way of doing stuff). I missed the part about print_r($_SESSION) . Can you actually $this->view->setVar('myValue', 'my session value'); and see if that works in other views / controllers.

To set a value to your session bag in one place you do:

$users = Users::find(array($conditions, 'bind' => $parameters));
    if (count($users) > 0) {
        $user           = new Phalcon\Session\Bag('user');
        $user->username = $username;
    }
}

And then to retrieve it else where in another controller and pass it as a variable to view:

$user = new Phalcon\Session\Bag('user');
$this->view->setVar('userName', $user->username);

And then in the volt view to print it:

{% if username %}
    <input type="submit" name="Button" value="{{ username }}">
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM