Laravel basic tutorial-Session

Source: Internet
Author: User
Tags mongodb driver laravel tutorial
Basic laravel tutorial-Session introduction

Because the HTTP driver is a stateless protocol, it usually means that the server cannot clearly understand the relationship between the current request user and the previous request user, session provides a cross-request user solution. Laravel comes with a concise and unified API to support various backend session drivers. Laravel provides out-of-the-box support for popular backend drivers such as Memcached, Redis, and databases.

Configuration

The session configuration file is stored in config/session. php. Make sure to read the configuration item comments in this file before use. Laravel gives a detailed comment on each item in the configuration. By default, laravel uses the file session driver, which is sufficient for most applications. However, memcached or redis memory-level drivers are recommended in the production environment, which will greatly improve the session performance of applications.

The session data of each request is stored in the location of the session driver you defined. The following drivers can be used out-of-the-box in laravel:

  • File-sessions is stored in storage/framework/sessions.
  • Cookie-sessions is stored in the encrypted cookies.
  • Database-sessions will be stored in the database used in your application.
  • Memcached/redis-sessions will be stored in a faster memory-level storage drive.
  • Array-sessions can be stored in PHP arrays and cannot be accessed across requests.

Note: The array driver is usually used for testing to avoid persistent session data.

Driver prerequisites

Database

When using the database session driver, you must first create a table to store session items. The following example shows the SCHEMA declaration of the database session driver table:

Schema::create('sessions', function ($table) {  $table->string('id')->unique();  $table->integer('user_id')->nullable();  $table->string('ip_address', 45)->nullable();  $table->text('user_agent')->nullable();  $table->text('payload');  $table->integer('last_activity');});

You can also use the session: table Artisan command to generate a database session-driven migration table:

php artisan session:tablecomposer dump-autoloadphp artisan migrate

Redis

Before using the Redis session driver, you must install predis/predis (~ 1.0 ).

Other Session considerations

The Laravel framework uses flash as a key in the session, so you should avoid using the key of this name to the session.

If you need to store the encrypted session data, you can set the encrypt option to true in the configuration file.

Basic usage

Access Session

First, let's access the session. We can access the session instance through an HTTP request. HTTP requests can be injected by using type prompts in the controller method. You should remember that the controller method dependency will be injected through the laravel service container:

 session()->get('key');     //   }}

When you retrieve a value from the session, you can also specify a default value to the second parameter of the get method. the default value will be returned if the session does not retrieve the value of the corresponding key. You can also pass Closure as the default value. if the corresponding key cannot be found, the value returned by Closure execution results will be used as the default value:

$value = $request->session()->get('key', 'default');$value = $request->session()->get('key', function () {  return 'default'; });

If you want to retrieve all values from the session, you can use the all method:

$data = $request->session()->all();

You can use the global help method session to retrieve and store values:

Route::get('home', function () {  // Retrieve a piece of data from the session...  $value = session('key');  // Store a piece of data in the session...  session(['key' => 'value']);});

Determine whether a session exists

You can use the has method to determine whether a session contains a certain item. If yes, true is returned:

if ($request->session()->has('user')) {  //}

Store data in sessions

Once you obtain the session instance, you have the ability to interact with the underlying data. you can use various instance methods to interact. For example, you can use the put method to store a new data item in the session:

$request->session()->put('key', 'value');

Items whose median value is an array when the content is pushed to the session

You can use the push method to push a new value to the item whose value is an array in the session. For example, if the user. teams key indicates the path of the array in the session, you can push new values to the array as follows:

$request->session()->push('user.teams', 'developers');

Retrieve and delete an item

The pull method will delete this item in the session while searching:

$value = $request->session()->pull('key', 'default');

Delete an item in a session

You can use the forget method to delete data in a session. if you want to remove all data in the session, you can use the flush method:

$request->session()->forget('key');$request->session()->flush();

Regenerate session ID

If you need to regenerate the session ID, you can use the regenerate method:

$request->session()->regenerate();
Flash data

Sometimes you want to store some data in the session, but you can only use it for the next request. after using it, it is eliminated. You can use the flash method. The data stored in the session can only be accessed in subsequent requests and deleted later. Flash data is usually used for temporary status messages:

$request->session()->flash('status', 'Task was successful!');

If you need to maintain flash data to more requests, you can use the reflash method to maintain all flash data to additional requests. If you only need to maintain the specified flash data, you can use the keep method:

$request->session()->reflash();$request->session()->keep(['username', 'email']);
Add a custom Session driver

You need to use the extend method of the Session mask to add additional session drivers to Laravel. You can call the extend method in the boot method of the service provider:

    

You should note that your custom session driver should implement the SessionHandlerInterface interface. This interface only contains several simple implementation methods. The structure of an implemented MongoDB driver should be the same as below:

     

These methods are not as difficult to understand as cached StoreInterface. So let's take a quick look:

  • The open method is generally used in file-based session storage systems. Laravel has a file session driver attached, so you almost don't need to add any code in this method. You can directly put it as an empty method. In fact, this is a poor interface design (we will discuss it later). PHP must implement this method.
  • The close method is similar to the open method. you can ignore it. it is not required for most drivers.
  • The read method should return the string version of the data associated with the session based on the given $ sessionId. You do not need to perform any serialization or other encoding operations during storage or retrieval, because laravel will perform the serialization service for you.
  • The destroy method should delete the associated data from the session storage.
  • The gc method should delete the expired data associated with the session according to the given $ lifetime UNIX timestamp. For systems with automatic expiration capabilities, such as Memcached and Redis, you can leave this method empty.

Once your session driver is registered. You can use the mongo driver in the config/session. php configuration file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.