Brief introduction to the session mechanism of Laravel

Source: Internet
Author: User
Tags class manager
Some days ago, in order to answer a question, went to study the source of Laravel, tell me about my harvest:
This is the source of the problem:
http://segmentfault.com/q/1010000003776645?_ea=365137

The laravel used in this article are all 5.1 versions.

Let's start by looking at how Laravel creates the session component.
First we can see that the Startsession class is registered in the kernerl.php (not to discuss Laravel's Di and IOC), and to see how this class is used.

Session Start

Our handle method in this class sees the following code

Public function handle ($request, Closure $next) {$this->sessionhandled = true; If A session driver has been configured, we'll need to start the session here Application.    Note that the Laravel sessions//does not make a use of PHP "native" sessions on any to since they is crappy.        if ($this->sessionconfigured ()) {$session = $this->startsession ($request);    $request->setsession ($session);    } $response = $next ($request); Again, if the session has been configured we'll need to close out of the session/So, the attributes could be per sisted to some storage medium.    We'll 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, the way to get the session in this startsession is getsession.

Get Session

It uses the Laravel injected SessionManager the fully qualified name of this class is: \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;}

As we see in this function, it calls the SessionManager drive method, which is defined in the parent class manager of SessionManager and sees its implementation like this

/** * Get a driver instance. * * @param string $driver * @return Mixed */public function driver ($driver = null) {$driver = $driver?: $this->ge    Tdefaultdriver (); If the given driver have not been created before, we'll 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 ($drive r) {$method = ' create '. Ucfirst ($driver). '    Driver '; We ll check to see if a creator method exists for the given driver. If not we//would check for a custom driver creator, which allows developers to create//drivers using their own CU Stomized Driver CreatorClosure 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, calling the Getdefaultdriver method

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

Here is the driver field we defined in app/config/session.php, get this field, we can see from Createdriver source, it is actually called Createxxxxdriver way to get to driver.

OK, let's look at the simplest file, the 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 '] [' Sessi    On.files ']; Return $this->buildsession (new Filesessionhandler ($this->app[' files '], $path));} /** * Build the session instance. * * @param \sessionhandlerinterface $handler * @return \illuminate\session\store */protected function buildsession ($hand LER) {if ($this->app[' config '] [' session.encrypt ']) {return new Encryptedstore ($this->app[' con    Fig '] [' Session.cookie '], $handler, $this->app[' encrypter ');    } else {return new Store ($this->app[' config ' [' Session.cookie '], $handler); }}

This store is the entity of our session, and its specific read-write calls are made using abstract handler, that is, if the file is read, new Filehandler if Redis is new Redishandler implement read and write.

Session ID

Back to startsession This class, we look at GetSession this method

$session->setid ($request->cookies->get ($session->getname ()));

People who know the web should know that the session is based on the key stored in the cookie to differentiate between different sessions, so SessionID is especially important, here we don't care how cookies are read, We know that it is enough to read the SessionID stored in the cookie here.

Then see how to load the data

Data

is still the Startsession class,
We look at Startsession this method, the next sentence is called $session->start (); What is this sentence for? After the previous analysis, we know that $session is already a store object, then 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 [];} 

Call the Loadsession and Readfromhandler in turn, you can see from the handler call the Read method, this method is from the various handler we have defined before reading data, it is an abstract method, in the subclass of the concrete implementation, It is then returned to the store (in the attributes array in the store, so far, the session initialization method is over,

Public function Get ($name, $default = null) {    return arr::get ($this->attributes, $name, $default);}

This function reads the data in the session.

Summary

Ok,session the entire initialization process is summarized below:

sessionmanager#, Startsession#getsession, Startsession#handle, Startsession#startsession, Store#startsession, Store#setid, Getdefaultdriver, Sessionmanager#createxxxhandler,

Laravel clever use of object-oriented interface, provides us with a variety of different storage methods, once we understand the storage mode and encryption rules, so that different web containers for the purpose of session sharing can be achieved ~

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