Introduction to Laravel's Session mechanism

Source: Internet
Author: User
Laravel's Session mechanism was introduced a few days ago. to answer a question, I studied Laravel's source code and explained my gains:
This is the source of the problem:
Http://segmentfault.com/q/1010000003776645? _ Ea = 365137

All Laravel mentioned in this article uses version 5.1.

First, let's look at how Laravel creates the Session component.
First, we can see that the StartSession class is registered in Kernerl. php (we will not discuss DI and IoC of Laravel here), and we can see how this class is used.

Session Start

The handle method in this class shows the following code:

public function handle($request, Closure $next){    $this->sessionHandled = true;    // If a session driver has been configured, we will need to start the session here    // so that the data is ready for an application. Note that the Laravel sessions    // do not make use of PHP "native" sessions in any way since they are crappy.    if ($this->sessionConfigured()) {        $session = $this->startSession($request);        $request->setSession($session);    }    $response = $next($request);    // Again, if the session has been configured we will need to close out the session    // so that the attributes may be persisted to some storage medium. We will also    // add the session identifier cookie to the application response headers now.    if ($this->sessionConfigured()) {        $this->storeCurrentUrl($request, $session);        $this->collectGarbage($session);        $this->addCookieToResponse($response, $session);    }    return $response;}

OK, a typical filter. in this StartSession, getSession is used to obtain the Session.

Get Session

It uses the SessionManager class injected by Laravel. The full qualified names of this class are \ Illuminate \ Session \ SessionManager.

/** * Start the session for the given request. * * @param  \Illuminate\Http\Request  $request * @return \Illuminate\Session\SessionInterface */protected function startSession(Request $request){    with($session = $this->getSession($request))->setRequestOnHandler($request);    $session->start();    return $session;}/** * Get the session implementation from the manager. * * @param  \Illuminate\Http\Request  $request * @return \Illuminate\Session\SessionInterface */public function getSession(Request $request){    $session = $this->manager->driver();    $session->setId($request->cookies->get($session->getName()));    return $session;}

In this function, we can see that it calls the drive method of SessionManager. the drive method is defined in the parent class Manager of SessionManager, and its implementation is as follows:

/** * Get a driver instance. * * @param  string  $driver * @return mixed */public function driver($driver = null){    $driver = $driver ?: $this->getDefaultDriver();    // If the given driver has not been created before, we will create the instances    // here and cache it so we can return it next time very quickly. If there is    // already a driver created by this name, we'll just return that instance.    if (! isset($this->drivers[$driver])) {        $this->drivers[$driver] = $this->createDriver($driver);    }    return $this->drivers[$driver];}/** * Create a new driver instance. * * @param  string  $driver * @return mixed * * @throws \InvalidArgumentException */protected function createDriver($driver){    $method = 'create'.ucfirst($driver).'Driver';    // We'll check to see if a creator method exists for the given driver. If not we    // will check for a custom driver creator, which allows developers to create    // drivers using their own customized driver creator Closure to create it.    if (isset($this->customCreators[$driver])) {        return $this->callCustomCreator($driver);    } elseif (method_exists($this, $method)) {        return $this->$method();    }    throw new InvalidArgumentException("Driver [$driver] not supported.");}

That is, call the getdefadriver driver method.

/** * Get the default session driver name. * * @return string */public function getDefaultDriver(){    return $this->app['config']['session.driver'];}

Here we are at app/config/session. the driver field defined in php. after obtaining this field, we can see from the source code of createDriver that it actually gets the driver by calling createXXXXDriver.

OK. Let's take a look at the simplest File, that is, createFileDriver.

/** * Create an instance of the file session driver. * * @return \Illuminate\Session\Store */protected function createFileDriver(){    return $this->createNativeDriver();}/** * Create an instance of the file session driver. * * @return \Illuminate\Session\Store */protected function createNativeDriver(){    $path = $this->app['config']['session.files'];    return $this->buildSession(new FileSessionHandler($this->app['files'], $path));}/** * Build the session instance. * * @param  \SessionHandlerInterface  $handler * @return \Illuminate\Session\Store */protected function buildSession($handler){    if ($this->app['config']['session.encrypt']) {        return new EncryptedStore(            $this->app['config']['session.cookie'], $handler, $this->app['encrypter']        );    } else {        return new Store($this->app['config']['session.cookie'], $handler);    }}

This Store is the entity of our Session. its specific read/write calls are carried out using abstract Handler, that is, if it is a read file, for new FileHandler, if it is Redis, it is the new RedisHandler to implement read and write.

Session ID

Return to the StartSession class. let's look at the getSession method.

 $session->setId($request->cookies->get($session->getName()));

Users who know the Web should know that sessions are differentiated based on the key stored in the cookie, so sessionId is particularly important. here we do not care how the Cookie is read, we know that it is enough to read the SessionId stored in the cookie.

Next let's see how to load data.

Data

It is still the StartSession class,
Let's take a look at the startSession method. the next sentence is $ session-> start ();. why? After the previous analysis, we know that $ session is already a Store object, and its start method is as follows:

public function start(){    $this->loadSession();    if (! $this->has('_token')) {        $this->regenerateToken();    }    return $this->started = true;}/** * Load the session data from the handler. * * @return void */protected function loadSession(){    $this->attributes = array_merge($this->attributes, $this->readFromHandler());    foreach (array_merge($this->bags, [$this->metaBag]) as $bag) {        $this->initializeLocalBag($bag);        $bag->initialize($this->bagData[$bag->getStorageKey()]);    }} /** * Read the session data from the handler. * * @return array */protected function readFromHandler(){    $data = $this->handler->read($this->getId());    if ($data) {        $data = @unserialize($this->prepareForUnserialize($data));        if ($data !== false && $data !== null && is_array($data)) {            return $data;        }    }    return [];}

LoadSession and readFromHandler are called in sequence. we can see that the read method is called from handler. this method is to read data from various handler defined previously. it is an abstract method, the specific implementation in the subclass is then returned to Store (stored in the attributes array in the Store, so far, the Session initialization method has ended,

public function get($name, $default = null){    return Arr::get($this->attributes, $name, $default);}

This function reads data from the Session.

Summary

OK. summary of the entire Session initialization process:

StartSession # handle-> StartSession # startSession-> StartSession # getSession-> SessionManager # getdefadriver driver-> SessionManager # createXXXHandler-> Store # setId-> Store # startSession

Laravel cleverly uses the object-oriented interface method, providing us with a variety of different storage methods. once we understand the storage methods and encryption rules, so that different web containers can share sessions ~

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.