Lumen框架 之加入session
一、修改Lumen
1、打开bootstrap/app.php,在相应位置添加注册SessionServiceProvider
$app->register(Illuminate\Session\SessionServiceProvider::class);
2、同样在bootstrap/app.php中添加配置代码
$app->configure('session');
3、打开bootstrap/app.php,在Register Middleware位置修改
$app->middleware([ // App\Http\Middleware\ExampleMiddleware::class, Illuminate\Session\Middleware\StartSession::class ]);
4、修改别名,因为框架中使用了session别名,所以需要添加alias,不然会报错
$app->alias('session', 'Illuminate\Session\SessionManager');
5、在项目根目录创建config文件夹,并新建session.php配置文件
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, ];
二、简单使用
1、web.php路由文件
<?php /** @var \Laravel\Lumen\Routing\Router $router */ /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */ $router->group(['middleware' => 'test'], function () use ($router) { $router->get('/', function () use ($router) { return $router->app->version() .' - '. app('session')->get('username', ''); }); }); $router->get('/test', ['uses' => 'ExampleController@show']); $router->get('/login', ['uses' => 'ExampleController@login']); $router->get('/logout', ['uses' => 'ExampleController@logout']);
2、ExampleController
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class ExampleController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { } // public function show() { $admin = DB::table('blog_admin')->forPage(1,10)->get()->toArray(); //var_dump($admin); $username = app('session')->get('username', ''); //var_dump($username); //echo response()->json($admin); return view('test.test', ['name' => $username]); } public function login() { $res = app('session')->put('username', 'yy123'); //var_dump(app('session'));exit; return redirect('/'); } public function logout() { app('session')->put('username', ''); return redirect('/test'); } }
3、ExampleMiddleware.php
<?php namespace App\Http\Middleware; use Closure; class ExampleMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $username = app('session')->get('username'); if(!$username) { return redirect('/test'); } return $next($request); } }
4、app.php
$app->routeMiddleware([ //'auth' => App\Http\Middleware\Authenticate::class, 'test' => App\Http\Middleware\ExampleMiddleware::class ]);