Lumen中启用session
原文鏈接:http://www.jianshu.com/p/dc33f8ab0618
Lumen5.2 的Release Notes中官方明確的指出Lumen專注于構建無狀態API,JSON API 服務,移除了session和view的支持,但其實view還是存在的,session確實真的被移除了
因為項目需要所以我決定找回session,雖然官方建議需要session功能時可以使用強大的Laravel框架,但是對我小項目確實有點大材小用了。因為喜歡Laravel的優雅,所以我在小項目中都會把Lumen做為項目的首選。
下面就來一步步找回“丟失”的session吧!
注冊SessionServiceProvider
打開bootstrap/app.php,在相應位置添加注冊SessionServiceProvider,代碼如下
/*|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
*/ // 注冊 SessionServiceProvider $app->register(Illuminate\Session\SessionServiceProvider::class);
// 載入session相關配置 $app->configure('session');
configure函數會從文件中加載配置,并綁定到container中,接下來只需要在項目根目錄創建config文件夾,并新建session.php配置文件
<?php /*** Created by PhpStorm.* User: Spectre* Date: 2017/6/19* Time: 11:40*/ return ['driver' => env('SESSION_DRIVER', 'file'),//默認使用file驅動,你可以在.env中配置'lifetime' => 120,//緩存失效時間'expire_on_close' => false,'encrypt' => false,'files' => storage_path('framework/session'),//file緩存保存路徑'connection' => null,'table' => 'sessions','lottery' => [2, 100],'cookie' => 'laravel_session','path' => '/','domain' => null,'secure' => false, ];然后在storage/framework/下建立session文件夾用來存儲session緩存,別忘了修改權限
注冊StartSession中間件
打開bootstrap/app.php,在Register Middleware位置修改
// bootstrap/app.php // ... |-------------------------------------------------------------------------- | Register Middleware |-------------------------------------------------------------------------- // ... $app->middleware([Illuminate\Session\Middleware\StartSession::class ]);添加Session別名
因為框架中使用了session別名,所以需要添加alias,不然會報錯
// bootstrap/app.php // ... // 注冊 SessionServiceProvider $app->register(Illuminate\Session\SessionServiceProvider::class);// 載入session相關配置 $app->configure('session');// 設置session別名 $app->alias('session', 'Illuminate\Session\SessionManager');使用session
至此,你就可以在代碼中使用session了,使用 app('session') 即可獲取session實例,示例:
$request->session()->set('user', $users);$request->session()->get('user');?
轉載于:https://www.cnblogs.com/spectrelb/p/7048084.html
總結
以上是生活随笔為你收集整理的Lumen中启用session的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单的使用Seajs
- 下一篇: echarts 柱状图