08. SessionServiceProvider 详解
xiaohuilam opened this issue · comments
前言还没想好。
服务提供者部分
SessionServiceProvider
没有 boot
方法,其 register
方法为
作用
-
单例注册
Illuminate\Session\SessionManager
为session
-
单例注册
Illuminate\Session\Store
为session.store
具体生成
Illuminate\Session\Store
对象的过程,由你.env
配置SESSION_DRIVER
而调用Illuminate\Session\SessionManager
不同方法:createArrayDriver
createCookieDriver
createFileDriver
createNativeDriver
其实createFileDriver
就是调用的此方法createDatabaseDriver
createApcDriver
createMemcachedDriver
createRedisDriver
-
单例注册
Illuminate\Session\Middleware\StartSession
中间件
下面,我们以 SESSION_DRIVER=file
继续分析
当 SESSION_DRIVER
为 file
时,会调用到 createFileDriver
createFileDriver
调用了 createNativeDriver
这里 $this->app['config']['session.files']
得到的是
Line 60 in ca57c28
然后通过此处实例化 Illuminate\Session\FileSessionHandler
然后调用 buildSession
获得 \Illuminate\Session\Store
对象
laravel/vendor/laravel/framework/src/Illuminate/Session/SessionManager.php
Lines 163 to 170 in ca57c28
session 功能 / 操作部分
读取 session
当触发 Session::start
时,
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 69 to 78 in ca57c28
调用的 loadSession
为
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 85 to 88 in ca57c28
调用的 readFromHandler
为
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 95 to 106 in ca57c28
这里的 read
方法,就是 FileSessionHandler::read
执行到这里时, session 中的数据就被存放到了 Illuminate\Session\Store::$attributes
了。
而执行 Session::get
时,
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 205 to 208 in ca57c28
正好就能从 Store::$attributes
中取出 session 的数据了。
写入 session
当我们使用 Illuminate\Support\Facades\Session
时,操作是调用到的 session
,也就是 Illuminate\Session\SessionManager
。但是在 Illuminate\Support\Manager
的 __call
魔术方法,实现了将 session.driver
载入到 session
中被执行的能力。
laravel/vendor/laravel/framework/src/Illuminate/Support/Manager.php
Lines 144 to 147 in ca57c28
有兴趣的同学请阅读 15. Laravel 神奇的 Manager 类
假如我们执行 Session::put('key', 'value')
会穿透到
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 265 to 274 in ca57c28
当我们手动 Session::save
时,或者程序终止运行触发 register_shutdown_function
时,会触发
laravel/vendor/laravel/framework/src/Illuminate/Session/Store.php
Lines 124 to 133 in ca57c28
也就是 FileSessionHandler::write
至此,写入 session 的流程走完。