Laravel 5.1 Source Reading notes

Source: Internet
Author: User
Tags auth bootstrap classes closure mixed php source code

by Liigo. 20151105.

Installing, and creating items, are all passed composer, simple, skipped. Entry && Kernel

Site entry file, ${laravel-project}/public/index.php:

$app = require_once __dir__. ' /.. /bootstrap/app.php ';

$kernel = $app->make (illuminate\contracts\http\kernel::class);

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

$response->send ();

$kernel->terminate ($request, $response);

Generate request, Process request (Http\kernel::handle ()), generate response, send resonse. The general web processing process.

Note that Illuminate\contracts\http\kernel is just a interface:

Interface Kernel
{public
    function bootstrap ();
    Public function handle ($request);
    Public function Terminate ($request, $response);
    Public function getapplication ();
}

The code in the visible entry file, $kernel = $app->make is the key, followed by the instance object method that calls the Kerenl interface (especially Kernel::handle ()).

But $app who created it. What type is it? Bootstrap && Application

First line of code for the portal file:

$app = require_once __dir__. ' /.. /bootstrap/app.php ';

Guide us to see bootstrap/app.php source code, not many, take a look at it:

$app = new Illuminate\foundation\application
    realpath (__dir__. ' /.. /')
);

$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 $app;

The first line is created and the last row is returned. Now we know that $app is an object of the Illuminate\foundation\application type. (Because of require_once, $app is a single Instance object.) The middle line of code may be useful later, temporarily ignored here. )

Naturally, $kernel = $app->make () is called Applicaton::make (), the code takes a look:

/**
 * Resolve The given type from the container.
 * (overriding Container::make)
 * @return Mixed
/Public function make ($abstract, array $parameters = []) 
  {
    $abstract = $this->getalias ($abstract);

    if (Isset ($this->deferredservices[$abstract])) {
        $this->loaddeferredprovider ($abstract);
    }

    Return Parent::make ($abstract, $parameters);
}

However, it is unclear exactly which type it returns.

Against the previous bootstrap code:

$app->singleton (
    illuminate\contracts\http\kernel::class,
    app\http\kernel::class
);

We infer that $kernel = The true type of the $app->make () is App\http\kernel (the interface Illuminate\contracts\http\kernel is implemented simultaneously).
This inference is easy to prove, omitting the details here ($app->singleton->bind->alias->make ()).
The more specific details of creating kernel objects are trivial, and we also ignore the code that is interested in looking at the parent class method Illuminate\container\container::make ()/build ().

Now we summarize: first new Application type Object app, App,app create kernel type Object kernel, Kernel,kernel process request, generate response and send to client.

Additional: $app is directly new (new Illuminate\foundation\application), its constructor does some important initialization work, the collation code is as follows:

Public function __construct ($basePath = null)
{
    $this->instance (' app ', $this);
    $this->instance (' Illuminate\container\container ', $this);
    $this->register (New Eventserviceprovider ($this));
    $this->register (New Routingserviceprovider ($this));
    // ...
    $this->setbasepath ($basePath);
}
kernel::handle () && request=>response

Next I want to know $response = what is done inside $kernel->handle ($request), how to process the request and generate response.

As we have already analyzed before, the true type of $kernel is App\http\kernel, also implements the interface Illuminate\contracts\http\kernel.

Take App\http\kernel::handle () source code to see, gee, there is no such method.
See its parent class with the same name Method Illuminate\foundation\http\kernel::handle () code:

Public function handle ($request)
{
    try {
        $request->enablehttpmethodparameteroverride ();
        $response = $this->sendrequestthroughrouter ($request);
    catch (...) {
        // ...
    }
    $this->app[' Events ']->fire (' kernel.handled ', [$request, $response]);
    return $response;
}

I am interested in the above code only Sendrequestthroughrouter ($request) This call, go in and see:

/**
 * Send The given request through the Middleware/router.
 * *
 @param  \illuminate\http\request  $request
 * @return \illuminate\http\response
* * protected function Sendrequestthroughrouter ($request)
{
    $this->app->instance (' request ', $request);

    Facade::clearresolvedinstance (' request ');

    $this->bootstrap (); //! Note: $kernel->bootstrap ();

    Return (new Pipeline ($this->app))
                ->send ($request)
                ->through ($this->app-> Shouldskipmiddleware ()? []: $this->middleware)
                ->then ($this->dispatchtorouter ());
}

The last line in the code above is our focus, which sends the request to a newly created assembly line (Pipeline),
For each middleware (middleware) to be processed and sent to the router (Router). An analysis will be carried out below. Pipeline && middleware && Router

pipelining, middleware, routers. Pipleline

The pipeline Illuminate\pipeline\pipeline implements the interface Illuminate\contracts\pipeline\pipeline.
The main interface method is Send,through,via,then. Where send set Request object, through set middleware array, via set method name (default is "handle"), then finally run this and execute the closure parameters (then code is extremely complex, various closures nested, confuse me, interested friends can look at).

Simple inference, its work is: Call the handle method of each middleware in turn. In particular, if a middleware is a closure, it is called in the form of a closed packet. Middleware

The middleware Illuminate\contracts\routing\middleware is a very simple interface:

Interface middleware
{
    /**
     * Handle an incoming request.
     * *
     @param  \illuminate\http\request  $request
     * @param  \closure  $next
     * @return Mixed
     *
    /Public Function handle ($request, Closure $next);
}

Its documentation is also extremely crude and does not see much valuable information. What does the second argument mean, return the value what meaning, the ghost can see out. It may be necessary to start research on middleware from somewhere else. Router

The call process to send the request to Router: $kernel->handle ($request) => $kernel->sendrequestthroughrouter => $kernel-> Dispatchtorouter () => $kernel->router->dispatch ($request).

Where $kernel->router is the router object passed through the constructor when the $kernel is created.

It is necessary to look at how router was created first. Call Flow: $app = new Applicaton (__construct) => $app->register (New Routingserviceprovider ($app)) => Routingserviceprovider->register ()->registerrouter ().

protected function Registerrouter ()
{
    $this->app[' router '] = $this->app->share (function ($app) { return
        new Router ($app [' Events '], $app);}
    ;
}
unresolved

assembly line How to call the middleware, how to send routers, routers are how to work. There's a lot of detail in the middle of it that hasn't been figured out.

The assembly line there, the code is very winding, temporarily cannot understand. Middleware there, the document is too crude to understand for the time being. How the router works there is no code to look at for the time being.

This is the way it is, so this is the end of the article. I think I need to take a look at Laravel 5.1 of the basic document, and then go back to read the source code, may be more effective. fill in the Notes Bootstrap

When I was analyzing kernel::handle (), I ignored a place where kernel::sendrequestthroughrouter () called the Kernel::bootstrap () method internally:

/**
 * Bootstrap the application for HTTP requests.
 *
 * @return void */public
function bootstrap ()
{
    if (! $this->app->hasbeenbootstrapped ()) {
        $this->app->bootstrapwith ($this->bootstrappers ());
    }

Kernel::bootstrap () internally called the Applicaton::bootstrapwith ():

/**
 * Run The given array of bootstrap classes.
 *
 @param  array  $bootstrappers
 * @return void *
 /public
function Bootstrapwith (array $bootstrappers)
{
    $this->hasbeenbootstrapped = true;

    foreach ($bootstrappers as $bootstrapper) {
        $this [' Events ']->fire (' bootstrapping: '. $bootstrapper, [$this]);

        $this->make ($bootstrapper)->bootstrap ($this);

        $this [' Events ']->fire (' bootstrapped: '. $bootstrapper, [$this]);
    }

The Applicaton::bootstrapwith () parameter is kernel::bootstrappers (), and its initial value is:

/**
 * The bootstrap classes for the application.
 *
 * @var array
 /
protected $bootstrappers = [
    ' illuminate\foundation\bootstrap\detectenvironment ',
    ' illuminate\foundation\bootstrap\loadconfiguration ',
    ' illuminate\foundation\bootstrap\ Configurelogging ',
    ' illuminate\foundation\bootstrap\handleexceptions ', '
    illuminate\foundation\ Bootstrap\registerfacades ',
    ' illuminate\foundation\bootstrap\registerproviders ', '
    illuminate\ Foundation\bootstrap\bootproviders ',
];

In the example of Registerproviders, the bootstrap () method calls $app->registerconfiguredproviders ():

Public Function registerconfiguredproviders ()
{
    $manifestPath = $this->getcachedservicespath ();

    (New Providerrepository ($this, new filesystem, $manifestPath))
                ->load ($this->config[' app.providers ');
}

Where the value of $this->config[' App.providers ' comes from file config/app.php:

' Providers ' => [* * laravel Framework Service providers ... * * Illuminate\foundation\providers\arti Sanserviceprovider::class, Illuminate\auth\authserviceprovider::class, illuminate\broadcasting\ Broadcastserviceprovider::class, Illuminate\bus\busserviceprovider::class, Illuminate\cache\cacheserviceprovider :: Class, Illuminate\foundation\providers\consolesupportserviceprovider::class, illuminate\routing\ Controllerserviceprovider::class, Illuminate\cookie\cookieserviceprovider::class, Illuminate\Database\ Databaseserviceprovider::class, Illuminate\encryption\encryptionserviceprovider::class, Illuminate\Filesystem\ Filesystemserviceprovider::class, Illuminate\foundation\providers\foundationserviceprovider::class, Illuminate\ Hashing\hashserviceprovider::class, Illuminate\mail\mailserviceprovider::class, Illuminate\Pagination\
  Paginationserviceprovider::class, Illuminate\pipeline\pipelineserviceprovider::class,  Illuminate\queue\queueserviceprovider::class, Illuminate\redis\redisserviceprovider::class, Illuminate\Auth\Pass Words\passwordresetserviceprovider::class, Illuminate\session\sessionserviceprovider::class, Illuminate\
    Translation\translationserviceprovider::class, Illuminate\validation\validationserviceprovider::class, Illuminate\view\viewserviceprovider::class, * * Application Service Providers ... * * App\providers\apps Erviceprovider::class, App\providers\authserviceprovider::class, App\providers\eventserviceprovider::class, Ap P\providers\routeserviceprovider::class,],

As we all see, kernel and application cross call each other, and the bootstrap process is interspersed between the request processing process. I can't see a clear idea for a while. References

Laravel is not a small project, the logic is complex, after dividing the module, the layout is dispersed. It is very difficult for you to simply browse through the source code in a short period of time to clarify the design idea of the frame body, especially in the case of laravel still unfamiliar to me. Moderation is the choice of reason.

First look at the basic documents: Http://laravel.com/docs/5.1/lifecycle Http://laravel.com/docs/5.1/providers http://laravel.com/ Docs/5.1/container Http://laravel.com/docs/5.1/middleware http://laravel.com/docs/5.1/requests http://laravel.com /docs/5.1/responses http://laravel.com/docs/5.1/routing

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.