The life cycle and principle analysis of laravel frame

Source: Internet
Author: User
This article mainly introduces the life cycle and principle of laravel framework, and summarizes and analyzes the complete operation cycle, process and principle of Laravel framework for user request response, with the example form, which can be referenced by friends.

This paper describes the life cycle and principle of laravel framework. Share to everyone for your reference, as follows:

Introduction:

If you are familiar with the use of a tool, then you will be confident when using this tool!

Body:

Once the user (browser) sends an HTTP request, our Apache or nginx will generally go to index.php, so the following series of steps are starting from index.php, let's take a look at this file code.

<?phprequire __dir__. ' /.. /bootstrap/autoload.php '; $app = require_once __dir__. ' /.. /bootstrap/app.php ';/*|--------------------------------------------------------------------------| Run the application|--------------------------------------------------------------------------| | Once we have the application, we can handle the incoming request| Through the kernel, and send the associated response back to| The client ' s browser allowing them to enjoy the creative| and wonderful application we have prepared for them.| */$kernel = $app->make (illuminate\contracts\http\kernel::class), $response = $kernel->handle (  $request = Illuminate\http\request::capture ()); $response->send (); $kernel->terminate ($request, $response);

In the comments, the author talks about the role of kernel, the role of kernel, kernel processing a request for a visit, and sending a corresponding return to the user's browser.

Here again involves an App object, so attach the App object, so attach the source code of the App object, this source code is \bootstrap\app.php

<?php/*|--------------------------------------------------------------------------| Create the application|--------------------------------------------------------------------------| | The first thing we'll do is create a new Laravel application instance| Which serves as the "glue" for all the components of Laravel, and is| The IoC container for the system binds all of the various parts.| */$app = new Illuminate\foundation\application (Realpath (__dir__. ') /.. /'));/*|--------------------------------------------------------------------------| Bind Important interfaces|--------------------------------------------------------------------------| | Next, we need to bind some important interfaces into the container so| We'll be able to resolve them when needed. The kernels serve the| Incoming requests to this application from both the Web and cli.|  */$app->singleton (Illuminate\contracts\http\kernel::class, app\http\kernel::class); $app->singleton ( Illuminate\contracts\console\kerNel::class, App\console\kernel::class); $app->singleton (Illuminate\contracts\debug\exceptionhandler::class, App\exceptions\handler::class);/*|--------------------------------------------------------------------------| Return the application|--------------------------------------------------------------------------| | This script returns the application instance. The instance is given to| The calling script so we can separate the building of the instances| From the actual running of the application and sending responses.| */return $app;

See the app variable is the object of the Illuminate\foundation\application class, so call the constructor of this class, specifically do what matter, we look at the source code.

Public function __construct ($basePath = null) {  if ($basePath) {    $this->setbasepath ($basePath);  }  $this->registerbasebindings ();  $this->registerbaseserviceproviders ();  $this->registercorecontaineraliases ();}

The constructor does 3 things, the first two things are well understood, create container, register the serviceprovider, see the code

/** * Register The basic bindings into the container. * * @return void */protected function registerbasebindings () {  static::setinstance ($this);  $this->instance (' app ', $this);  $this->instance (Container::class, $this);} /** * Register All of the base service providers. * * @return void */protected function Registerbaseserviceproviders () {  $this->register (New Eventserviceprovider ($this));  $this->register (New Logserviceprovider ($this));  $this->register (New Routingserviceprovider ($this));}

The last thing is to do a very large array, defined a large number of aliases, the side of the show programmer is smart lazy people.

/** * Register the core class aliases in the container. * * @return void */public function registercorecontaineraliases () {$aliases = [' app ' = [\illuminate\found Ation\application::class, \illuminate\contracts\container\container::class, \illuminate\contracts\foundation\ Application::class], ' auth ' = [\illuminate\auth\authmanager::class, \ILLUMINATE\CONTRACTS\AUTH\FACTORY::CLA SS], ' auth.driver ' = [\illuminate\contracts\auth\guard::class], ' blade.compiler ' = [\illuminate\view\ Compilers\bladecompiler::class], ' cache ' = [\illuminate\cache\cachemanager::class, \ILLUMINATE\CONTRACTS\CAC He\factory::class], ' cache.store ' = [\illuminate\cache\repository::class, \illuminate\contracts\cache\reposito Ry::class], ' config ' = [\illuminate\config\repository::class, \illuminate\contracts\config\repository::class ], ' cookie ' = [\illuminate\cookie\cookiejar::class, \illuminate\contracts\cookie\factory::Class, \illuminate\contracts\cookie\queueingfactory::class], ' encrypter ' = [\illuminate\encryption\encrypter:: Class, \illuminate\contracts\encryption\encrypter::class], ' db ' = [\illuminate\database\databasemanager::c Lass], ' db.connection ' = [\illuminate\database\connection::class, \illuminate\database\connectioninterface::    Class], ' events ' = [\illuminate\events\dispatcher::class, \illuminate\contracts\events\dispatcher::class], ' Files ' = [\illuminate\filesystem\filesystem::class], ' Filesystem ' = [\illuminate\filesystem\file Systemmanager::class, \illuminate\contracts\filesystem\factory::class], ' filesystem.disk ' = [\Illuminate\ Contracts\filesystem\filesystem::class], ' filesystem.cloud ' = [\illuminate\contracts\filesystem\cloud::class] , ' hash ' = [\illuminate\contracts\hashing\hasher::class], ' translator ' = [\illuminate\translati On\translator::class, \illuminate\contraCts\translation\translator::class], ' log ' = [\illuminate\log\writer::class, \illuminate\contracts\logging\l Og::class, \psr\log\loggerinterface::class], ' mailer ' = [\illuminate\mail\mailer::class, \illuminate\contrac Ts\mail\mailer::class, \illuminate\contracts\mail\mailqueue::class], ' auth.password ' = [\Illuminate\Auth\ Passwords\passwordbrokermanager::class, \illuminate\contracts\auth\passwordbrokerfactory::class], ' Auth.password.broker ' = [\illuminate\auth\passwords\passwordbroker::class, \illuminate\contracts\auth\ Passwordbroker::class], ' queue ' = [\illuminate\queue\queuemanager::class, \illuminate\contracts\queue\factor Y::class, \illuminate\contracts\queue\monitor::class], ' queue.connection ' = [\illuminate\contracts\queue\queue :: Class], ' queue.failer ' = [\illuminate\queue\failed\failedjobproviderinterface::class], ' redirect ' =& Gt [\illuminate\routing\redirector::class], ' redis ' = [\illuminate\redis\redismanager::class, \illuminate\contracts\redis\factory::class], ' request ' = [\Illuminate\ Http\request::class, \symfony\component\httpfoundation\request::class], ' router ' = [\illuminate\routing\rout Er::class, \illuminate\contracts\routing\registrar::class, \illuminate\contracts\routing\bindingregistrar::class ], ' session ' = [\illuminate\session\sessionmanager::class], ' session.store ' = [\illuminate\session\ Store::class, \illuminate\contracts\session\session::class], ' url ' = = [\illuminate\routing\urlgenerator::cla SS, \illuminate\contracts\routing\urlgenerator::class], ' validator ' = [\illuminate\validation\factory::class, \illuminate\contracts\validation\factory::class], ' view ' = [\illuminate\view\factory::class, \Illuminate\Co  Ntracts\view\factory::class], ";    foreach ($aliases as $key = + $aliases) {foreach ($aliases as $alias) {$this->alias ($key, $alias); }  }} 

Here comes a instance function, which is not a function of the application class, but rather a function of the parent class container class of the application class.

/** * Register an existing instance as GKFX in the container. * * @param string $abstract * @param mixed  $instance * @return void */public Function instance ($abstract, $instance) { c1/> $this->removeabstractalias ($abstract);  unset ($this->aliases[$abstract]);  We'll check to determine if this type have been bound before, and if it has  //We'll fire the rebound callbacks re Gistered with the container and it  //can is updated with consuming classes that has gotten resolved here.  $this->instances[$abstract] = $instance;  if ($this->bound ($abstract)) {    $this->rebound ($abstract);  }}

Application is a subclass of container, so it is $app not only the object of the application class, but also the object of container, so the newly emerged Singleton Function we can go to the source code file of the container class to check. The difference between the bind function and the singleton is shown in this blog post.

Singleton This function, the previous argument is the actual class name, and the latter argument is the "Alias" of the class.

$appThe object declares 3 Singleton model objects, namely Httpkernel,consolekernel,exceptionhandler. Note that there is no object created here, just a declaration, just an "alias".

We have found that there is also a $kernel variable in index.php, but only save the make out of the Httpkernel variable, so this article is no longer discussed, Consolekernel,exceptionhandler ...

Continue to find app\http\kernel.phpunder the folder, since we put the actual httpkernel do things in this PHP file, from this code to see what actually did?

<?phpnamespace app\http;use Illuminate\foundation\http\kernel as Httpkernel;class Kernel extends HttpKernel{/** * T   He application ' s global HTTP middleware stack.   * * These middleware is run during every request to your application.     * * @var Array */protected $middleware = [\illuminate\foundation\http\middleware\checkformaintenancemode::class,  \app\http\middleware\mymiddleware::class,];   /** * The application ' s route middleware groups.      * * @var Array */protected $middlewareGroups = [' web ' = = [\app\http\middleware\encryptcookies::class, \illuminate\cookie\middleware\addqueuedcookiestoresponse::class, \illuminate\session\middleware\startsession::    Class, \illuminate\view\middleware\shareerrorsfromsession::class, \app\http\middleware\verifycsrftoken::class,  ], ' API ' = [' throttle:60,1 ',],];   /** * The application ' s route middleware. * * These middleware may is assigned to groups or used InpidUally. * * @var Array */protected $routeMiddleware = [' auth ' = = \app\http\middleware\authenticate::class, ' auth.b ASIC ' = \illuminate\auth\middleware\authenticatewithbasicauth::class, ' guest ' = \app\http\middleware\ Redirectifauthenticated::class, ' throttle ' = \illuminate\routing\middleware\throttlerequests::class, ' Mymiddleware ' =>\app\http\middleware\mymiddleware::class,];}

At a glance, the middleware array is defined in Httpkernel.

When the work is done, it begins the process of request to response, see index.php

$response = $kernel->handle (  $request = Illuminate\http\request::capture ()); $response->send ();

Finally, in the abort, release all resources.

/*** call the Terminate method on any terminable middleware.** @param \illuminate\http\request $request * @param \illuminat E\http\response $response * @return void*/public function Terminate ($request, $response) {    $this Terminatemiddleware ($request, $response);    $this->app->terminate ();}

To summarize, a simple summary of the whole process is:

1.index.php loads the \bootstrap\app.php, creates container in the constructor of the application class, registers serviceprovider, defines an array of aliases, Then use the app variable to save the object constructed by the constructor.

2. Using the App object, create 1 Singleton schema Object Httpkernel, call the constructor when creating Httpkernel, complete the declaration of the middleware.

3. All of the above work is done before requesting a visit, and the next step is to wait for the request, then: accept the request-- process the request -- Send a response -- abort the app variable

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.