How do sessions work in Laravel 5

2019-04-15 23:37发布

问题:

I am trying to understand how sessions work in Laravel 5(.4). In one hand there are two ways of using them as described in the official documentation:

There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.

$request->session()->put('key', 'value');

and

session(['key' => 'value']);

The documentation says:

There is little practical difference between using the session via an HTTP request instance versus using the global session helper.

But it is never explained what the difference is.

In the other hand there is the "Facade way":

Session::put('key', 'value');

And recently I found this Stack Overflow question How to use session in laravel 5.2 controller. train_fox pointed out this way:

session()->put('key', 'value');

So that makes a total of four ways. And I cannot figure out why or when use one or another. Does someone know the difference between those four?

By the way, the only way I could get sessions to work with Redis was with the two last ways.

Thank you in advance for your enlightenment.

回答1:

Let's consider Facade first:

Session::put('key', 'value');

This facades calls Illuminate\Session\Store::put().

Now let's consider the function session():

function session($key = null, $default = null)
{
    if (is_null($key)) {
        return app('session');
    }

    if (is_array($key)) {
        return app('session')->put($key);
    }
    // ...
}

Reading this, we can assume that session(['a' => 'b']) works similar that session()->put('a', 'b') (because if it's an array, it calls put on the same function).

app('session') returns Illuminate\Session\SessionManager (https://laravel.com/docs/5.4/facades#facade-class-reference). Illuminate\Session\SessionManager has a __call function which in short calls the driver of the session. So it's the same behavior.

Now the difference may be in the $request function vs all other ones (as it's written in docs). According to the source code it returns a \Symfony\Component\HttpFoundation\Session\SessionInterface. The SessionInterface has not the same methods as Illuminate\Session\Storeso maybe it's why it differs.

Ok I give up. It's hard to understand. I can't help you more, I'm lost. I keep this post for history need.