Session
brief introduction
College note: Rather than using PHP's built-in session function, Larave has implemented a more flexible and powerful session mechanism. Please refer to
Illuminate\Session\Middleware\StartSession This middleware, so do not try to pass the
$_SESSION Method to obtain the session value of the application, which is futile. In addition, there is a problem that everyone is puzzled about. It is impossible to obtain the application session data in the controller constructor of Laravel. This is because Laravel's session passes
StartSession The middleware starts. Since the middleware will be executed after the service container registers all services, and the constructors of the controllers are executed when the container registers services, the session has not been started at this time. Where can I get data? The solution is to post the logic of obtaining the session data or introduce the
StartSession Middleware executed later.
to configure
-
file – Session data is stored in storage/framework/sessions Directory; -
cookie – Session data is stored in a cookie that has been securely encrypted; -
database – Session data is stored in the database -
memcached / redis – The session data is stored in the Memcached/Redis cache, with the fastest access speed; -
array – Session data is stored in a simple PHP array and is non persistent between multiple requests.
Note: Array drive is usually used for Run Test To avoid session data persistence.
Drive preparatory knowledge
Schema::create('sessions', function ($table) { $table->string('id')->unique(); $table->unsignedInteger('user_id')->nullable(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->text('payload'); $table->integer('last_activity'); });
php artisan session:table php artisan migrate
Note:
SESSION_DRIVER=redis stay
.env Set in.
Use Session
get data
<? php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserController extends Controller{ /** *Display the properties of the specified user * * @param Request $request * @param int $id * @return Response */ public function show(Request $request, $id) { $value = $request->session()->get('key'); // } }
$value = $request->session()->get('key', 'default'); $value = $request->session()->get('key', function() { return 'default'; });
Route::get('home', function () { //Get data from session $value = session('key'); //Specify Default $value = session('key', 'default'); //Store data to session session(['key' => 'value']); });
Note: Request instances and auxiliary functions via HTTP
session There is no substantial difference in data processing. Both methods can be used in test cases
assertSessionHas Methods.
$data = $request->session()->all();
if ($request->session()->has('users')) { // }
if ($request->session()->exists('users')) { // }
Store data
//By calling the put method of the request instance $request->session()->put('key', 'value'); //Through the global auxiliary function session session(['key' => 'value']);
$request->session()->push('user.teams', 'developers');
$value = $request->session()->pull('key', 'default');
One time data
$request ->session() ->flash ('status', 'Successful login to Larave Academy!');
$request->session()->reflash(); $request->session()->keep(['username', 'email']);
Delete Data
$request->session()->forget('key'); $request->session()->flush();
Regenerate Session ID
$request->session()->regenerate();
Add custom session driver
Implementation drive
<? php namespace App\Extensions; class MongoSessionHandler implements SessionHandlerInterface { public function open($savePath, $sessionName) {} public function close() {} public function read($sessionId) {} public function write($sessionId, $data) {} public function destroy($sessionId) {} public function gc($lifetime) {} }
Note: Larravel does not include a directory for containing extensions by default. You can place extensions anywhere. Here we create a
Extensions The directory is used to store
MongoSessionHandler 。
-
open The method is used for the file based session storage system. Since Larvel already has a file Session driver, so you don't need to place any code in this method. You can set it as an empty method. -
close Like the open method, the method can also be ignored, which is not used by most drivers. -
read The method should return $sessionId The string version of the matched session data does not require any serialization or other encoding to obtain or store the session data from the driver, because Larvel has serialized it for us. -
write The method should give $data Write to the corresponding $sessionId , such as MongoDB, Dynamo, etc. Again, do not do any serialization operation. Laravel has already handled it for us. -
destroy Method to remove from persistent storage $sessionId Corresponding data. -
gc Method destruction is greater than given $lifetime This method can be left blank for systems with expiration mechanisms such as Memcached and Redis.
Registration Driver
<? php namespace App\Providers; use App\Extensions\MongoSessionHandler; use Illuminate\Support\Facades\Session; use Illuminate\Support\ServiceProvider; class SessionServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Session::extend('mongo', function($app) { // Return implementation of SessionHandlerInterface... return new MongoSessionHandler; }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }