gpt4 book ai didi

php - Laravel 5 中的 session 如何工作

转载 作者:行者123 更新时间:2023-12-04 03:12:47 25 4
gpt4 key购买 nike

我试图了解 Laravel 5(.4) 中的 session 是如何工作的。
一方面,有两种使用方式,如 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');


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

文档说:

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



但从来没有解释过有什么不同。

另一方面有“门面方式”:
Session::put('key', 'value');

最近我发现了这个堆栈溢出问题 How to use session in laravel 5.2 controller . train_fox这样指出:
session()->put('key', 'value');

所以总共有四种方式。我无法弄清楚为什么或何时使用一种或另一种。有人知道这四个的区别吗?

顺便说一句,我可以让 session 与 Redis 一起工作的唯一方法是使用最后两种方法。

预先感谢您的启发。

最佳答案

让我们首先考虑 Facade:

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

这个外墙叫 Illuminate\Session\Store::put() .

现在让我们考虑函数 session() :
function session($key = null, $default = null)
{
if (is_null($key)) {
return app('session');
}

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

读到这里,我们可以假设 session(['a' => 'b'])工作原理与 session()->put('a', 'b') 类似(因为如果它是一个数组,它会在同一个函数上调用 put)。
app('session')返回 Illuminate\Session\SessionManager ( https://laravel.com/docs/5.4/facades#facade-class-reference )。 Illuminate\Session\SessionManager有一个 __call简而言之调用 session 驱动程序的函数。所以这是相同的行为。

现在的区别可能在于 $request函数与所有其他函数(如文档中所写)。根据源代码它返回一个 \Symfony\Component\HttpFoundation\Session\SessionInterface . SessionInterfaceIlluminate\Session\Store 的方法不同所以也许这就是它不同的原因。

好吧我放弃了。很难理解。我帮不了你了,我迷路了。我保留这个帖子是为了历史需要。

关于php - Laravel 5 中的 session 如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com