Laravel source code analysis starts from the entrance

Time:2021-3-3

Laravel source code analysis starts from the entrance

preface

The way to improve your ability is not to use more tools, but to use your own tools. Today we start with the first step of laravel’s launch.

Import file

Laravel is a single entry framework, all requests must go through index.php

define('LARAVEL_ Start ', microtime (true)); // get the start time

Using composer is the hallmark of modern PHP

require __ DIR__ .'/../vendor/ autoload.php '; // load composer - > autoload.php

Load startup file

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

obtain$appIt’s the key to start laravel. It can also be said that $app is the key to start laravel kernel. The next step is to load the kernel, the entity classes mapped by the service provider and the facade, the middleware, and finally to receive the HTTP request and return the result.

$kernel = $app - > make (illuminate, contracts, HTTP, kernel:: class); // load the core class

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

$response->send();

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

The seemingly short four lines of code is the elegance of laravel. We started to dig deeper.

bootstrap\app.php

This boot file can also be regarded as a service provider, but it does not have boot and register methods. Because the entry file loads it directly, all these unnecessary methods do not exist.

As a startup file, the home page is all the necessary elements for loading the framework, such as

  • registerBaseBindings
  • registerBaseServiceProviders
  • registerCoreContainerAliases,

This includes many basic methods and classes, such as

  • db [\Illuminate\Database\DatabaseManager::class]
  • auth [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class]
  • log [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class]
  • queue [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class]
  • redis [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class]
  • wait ...

The core variable of $app in the service provider is the result of application instantiation, and the make, bind and singleton you use in the service provider come from its parent class container. It is said that container is the core concept of laravel. We will explain this concept in detail later.

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

Above, we have obtained the instantiation of $app. Now we register the core class and exception class through $app, and return $app toindex.php

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

App\Http\Kernel

The core class contains all the

  • Systems Middleware
  • Group Middleware
  • Routing Middleware

Of course, you need to use middleware, which is also loaded in this class. It is a file that is often used.

protected $middleware = [
            \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
            \App\Http\Middleware\TrimStrings::class,
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            \App\Http\Middleware\TrustProxies::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\Session\Middleware\AuthenticateSession::class,
                \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                \App\Http\Middleware\VerifyCsrfToken::class,
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],
            
            'api' => [
                'throttle:60,1',
                'bindings',
            ],
        ];

This core class inherits from its parent classIlluminate\Foundation\Http\Kernel::classThe core class does a lot of things, it will store all the middleware in a specified array, convenient for kernel calls and other class calls.

namespace App\Http;
    
use App\Api\Middleware\VerifyApiToken;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
    
class Kernel extends HttpKernel

Back to the starting point

Laravel’s startup has experienced a very complicated process. This is also the key to laravel’s elegance.

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

$response->send();

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

When the request is passed in, the whole laravel is started, and the result is returned by the developer through the controller or other accessible classes.

thank

Thank you for reading here, source code analysis of this article depends on personal understanding. If there is any discrepancy, please make bricks.

I hope this article can help you. thank you