[Laravel 5.2 Documentation] service-Session

Source: Internet
Author: User

1. Introduction

Because HTTP-driven applications are stateless, we use the session to store user request information. Laravel uses a clean, unified API to handle a variety of back-end session drivers, and currently supports popular back-end drivers including Memcached, Redis, and databases.

1.1 Configuration

The session configuration file is located in config/session.php. By default, the session driver used by Laravel is file-driven, which is not a problem for many applications. In a production environment, you might consider using memcached or Redis drivers for faster session performance.

The session driver defines where the session data for the request is stored, and Laravel can handle several types of drivers:

    • File–session data is stored in the Storage/framework/sessions directory;
    • Cookie–session data is stored in an encrypted and secure cookie;
    • Database–session data is stored in the database
    • Memcached/redis–session data is stored in the Memcached/redis;
    • Array–session data is stored in a simple PHP array and is non-persistent across multiple requests.

Note: Array drivers are typically used to run tests to avoid session data persistence.

1.2 Session Driver Readiness Knowledge

Database

When using the Databasesession driver, you need to set the table to contain the session entry, and here is the table structure declaration for that data table:

Schema::create (' Sessions ', function ($table) {    $table->string (' id ')->unique ();    $table->text (' payload ');    $table->integer (' last_activity ');});

You can use the Artisan command session:table to generate the migration:

PHP artisan session:tablecomposer dump-autoloadphp Artisan Migrate

Redis

Before using the Redis session driver in Laravel, you need to install the Predis/predis package via composer.

1.3 Other Session related issues

The Laravel framework uses the Flashsession key internally, so you should not add data items to the session by that name.

If you need all stored session data to be encrypted, set the Encrypt configuration to true in the configuration file.

2. Basic use

Visit session

First, we visit the session, we can access the session instance through the HTTP request, can introduce the request instance through the type hint in the Controller method, remember, the Controller method relies on the Laravel service container injection:

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

When fetching data from the session, you can also pass the default value as the second parameter to the Get method, and the default value is returned when the specified key does not exist in the session. If you pass a closure as the default to the Get method, the closure executes and returns the execution result:

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

If you want to get all the data from the session, you can use the All method:

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

You can also use the global PHP function session to get and store the data in the session:

Route::get (' Home ', function () {    //Get data from session ...    $value = Session (' key ');    Store data to session    ... session ([' key ' = ' value ']);});

Determine if a specified item exists in the session

The has method can be used to check whether the data item exists in the session. Returns True if present:

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

storing data in session

Once you get to the session instance, you can call multiple methods to interact with the underlying data, for example, the put method stores the new data into the session:

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

Push data to array session

The push method can be used to push data to a session whose value is an array, for example, if the User.teams key contains a team an array group, you can push the new value into the array like this:

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

Get and delete data

The Pull method will fetch and delete the data from the session:

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

Delete a data item from the session

The Forget method removes the specified data from the session, and if you want to remove all data from the session, you can use the Flush method:

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

Regenerate session ID

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

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

2.1 Disposable Data

Sometimes you may want to store data that is only valid in the next request in the session, which can be implemented by means of the Flash method. Session data stored using this method is only valid in subsequent HTTP requests and will then be deleted:

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

If you need to keep this one-time data in more requests, you can use the Reflash method, which holds all the one-time data to the next request, and if you just want to save a particular disposable data, you can use the Keep method:

$request->session ()->reflash (), $request->session ()->keep ([' username ', ' email ']);

3. Add a custom session driver

To add more drivers to the Laravel back end session, you can use the Extend method on the session façade. The method can be called in the service provider's boot method:

     

It is important to note that the custom session driver needs to implement the Sessionhandlerinterface interface, which contains a little bit of the method we need to implement, and a MongoDB implementation is as follows:

      

Since these methods are not as easy to understand as the cached Storeinterface interface approach, we'll go through each of these steps quickly:

    • The Open method is used for file-based session storage systems, and since Laravel already has one file session driver, there is no need to place any code in the method, so you can set it to an empty method.
    • The Close method, like the open method, can be ignored and is not available for most drivers.
    • The Read method should return a string version of the session data that matches the given $sessionid, and no serialization or other coding is required to fetch or store the session data from the drive, because Laravel has already serialized us.
    • The Write method should say that a given $data writes to the corresponding $sessionId of the persisted storage system, such as MongoDB, Dynamo, and so on.
    • The Destroy method removes the $sessionId corresponding data from the persisted storage.
    • The GC method destroys all session data that is larger than the given $lifetime, which can be left blank for systems that have outdated mechanisms of their own, such as Memcached and Redis.

Once the session driver is registered, the MONGO driver can be used in the configuration file config/session.php.

  • 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.