Analysis of the life cycle and principles of the Laravel framework

不言
Release: 2023-03-31 19:58:02
Original
1557 people have browsed it

This article mainly introduces the life cycle and principles of the Laravel framework. It summarizes and analyzes the complete operating cycle, process, and principles of the Laravel framework in response to user requests in the form of examples. Friends in need can refer to this article

The examples describe the life cycle and principles of the Laravel framework. Share it with everyone for your reference, the details are as follows:

Introduction:

If you know the principle of using a tool well, then you are Feel confident when using this tool!

Text:

Once the user (browser) sends an HTTP request, our apache or nginx usually goes to index.php , Therefore, the subsequent series of steps all start from index.php. Let's take a look at the code of this file first.

<?php
require __DIR__.&#39;/../bootstrap/autoload.php&#39;;
$app = require_once __DIR__.&#39;/../bootstrap/app.php&#39;;
/*
|--------------------------------------------------------------------------
| 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&#39;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);
Copy after login

The author talks about the role of the kernel in the comments. The kernel processes incoming requests and sends corresponding responses back to the user's browser.

An app object is involved here again, so the app object is attached, so the source code of the app object is attached. This source code is \bootstrap\app.php

<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will 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 binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
  realpath(__DIR__.&#39;/../&#39;)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will 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;
Copy after login

Please see that the app variable is an object of the Illuminate\Foundation\Application class, so the constructor of this class is called, and what is done specifically, let’s see Source code.

public function __construct($basePath = null)
{
  if ($basePath) {
    $this->setBasePath($basePath);
  }
  $this->registerBaseBindings();
  $this->registerBaseServiceProviders();
  $this->registerCoreContainerAliases();
}
Copy after login

The constructor does 3 things. The first two things are easy to understand. Create a Container and register a ServiceProvider. Look at the code

/**
 * Register the basic bindings into the container.
 *
 * @return void
 */
protected function registerBaseBindings()
{
  static::setInstance($this);
  $this->instance(&#39;app&#39;, $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));
}
Copy after login

The last thing is to make a large array and define a large number of aliases, which shows that programmers are smart lazy people.

/**
 * Register the core class aliases in the container.
 *
 * @return void
 */
public function registerCoreContainerAliases()
{
  $aliases = [
    &#39;app&#39;         => [\Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class],
    &#39;auth&#39;         => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],
    &#39;auth.driver&#39;     => [\Illuminate\Contracts\Auth\Guard::class],
    &#39;blade.compiler&#39;    => [\Illuminate\View\Compilers\BladeCompiler::class],
    &#39;cache&#39;        => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class],
    &#39;cache.store&#39;     => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::class],
    &#39;config&#39;        => [\Illuminate\Config\Repository::class, \Illuminate\Contracts\Config\Repository::class],
    &#39;cookie&#39;        => [\Illuminate\Cookie\CookieJar::class, \Illuminate\Contracts\Cookie\Factory::class, \Illuminate\Contracts\Cookie\QueueingFactory::class],
    &#39;encrypter&#39;      => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class],
    &#39;db&#39;          => [\Illuminate\Database\DatabaseManager::class],
    &#39;db.connection&#39;    => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class],
    &#39;events&#39;        => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class],
    &#39;files&#39;        => [\Illuminate\Filesystem\Filesystem::class],
    &#39;filesystem&#39;      => [\Illuminate\Filesystem\FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class],
    &#39;filesystem.disk&#39;   => [\Illuminate\Contracts\Filesystem\Filesystem::class],
    &#39;filesystem.cloud&#39;   => [\Illuminate\Contracts\Filesystem\Cloud::class],
    &#39;hash&#39;         => [\Illuminate\Contracts\Hashing\Hasher::class],
    &#39;translator&#39;      => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class],
    &#39;log&#39;         => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::class, \Psr\Log\LoggerInterface::class],
    &#39;mailer&#39;        => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\Mail\Mailer::class, \Illuminate\Contracts\Mail\MailQueue::class],
    &#39;auth.password&#39;    => [\Illuminate\Auth\Passwords\PasswordBrokerManager::class, \Illuminate\Contracts\Auth\PasswordBrokerFactory::class],
    &#39;auth.password.broker&#39; => [\Illuminate\Auth\Passwords\PasswordBroker::class, \Illuminate\Contracts\Auth\PasswordBroker::class],
    &#39;queue&#39;        => [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class],
    &#39;queue.connection&#39;   => [\Illuminate\Contracts\Queue\Queue::class],
    &#39;queue.failer&#39;     => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],
    &#39;redirect&#39;       => [\Illuminate\Routing\Redirector::class],
    &#39;redis&#39;        => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class],
    &#39;request&#39;       => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class],
    &#39;router&#39;        => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class],
    &#39;session&#39;       => [\Illuminate\Session\SessionManager::class],
    &#39;session.store&#39;    => [\Illuminate\Session\Store::class, \Illuminate\Contracts\Session\Session::class],
    &#39;url&#39;         => [\Illuminate\Routing\UrlGenerator::class, \Illuminate\Contracts\Routing\UrlGenerator::class],
    &#39;validator&#39;      => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class],
    &#39;view&#39;         => [\Illuminate\View\Factory::class, \Illuminate\Contracts\View\Factory::class],
  ];
  foreach ($aliases as $key => $aliases) {
    foreach ($aliases as $alias) {
      $this->alias($key, $alias);
    }
  }
}
Copy after login

There is an instance function here. In fact, this is not a function of the Application class, but a function of the Container class, the parent class of the Application class.

/**
 * Register an existing instance as shared in the container.
 *
 * @param string $abstract
 * @param mixed  $instance
 * @return void
 */
public function instance($abstract, $instance)
{
  $this->removeAbstractAlias($abstract);
  unset($this->aliases[$abstract]);
  // We&#39;ll check to determine if this type has been bound before, and if it has
  // we will fire the rebound callbacks registered with the container and it
  // can be updated with consuming classes that have gotten resolved here.
  $this->instances[$abstract] = $instance;
  if ($this->bound($abstract)) {
    $this->rebound($abstract);
  }
}
Copy after login

Application is a subclass of Container, so $app is not only an object of the Application class, but also an object of Container, so the new singleton function we can check in the source code file of the Container class. See this blog post for the difference between bind function and singleton.

singletonThis function, the first parameter is the actual class name, and the latter parameter is the "alias" of the class. The

$app object declares three singleton model objects, namely HttpKernel, ConsoleKernel, ExceptionHandler. Please note that no object is created here, it is just declared, and it is just an "alias" .

Have you noticed that there is also a $kernel variable in index.php, but only the HttpKernel variable produced by make is saved, so this article will not discuss ConsoleKernel and ExceptionHandler. . .

Continue to find App\Http\Kernel.php in the folder. Since we have written all the actual things done by HttpKernel in this php file, let’s look at this code See what exactly was done?

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
  /**
   * The application&#39;s global HTTP middleware stack.
   *
   * These middleware are run during every request to your application.
   *
   * @var array
   */
  protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    //\App\Http\Middleware\MyMiddleware::class,
  ];
  /**
   * The application&#39;s route middleware groups.
   *
   * @var array
   */
  protected $middlewareGroups = [
    &#39;web&#39; => [
      \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,
    ],
    &#39;api&#39; => [
      &#39;throttle:60,1&#39;,
    ],
  ];
  /**
   * The application&#39;s route middleware.
   *
   * These middleware may be assigned to groups or used inpidually.
   *
   * @var array
   */
  protected $routeMiddleware = [
    &#39;auth&#39; => \App\Http\Middleware\Authenticate::class,
    &#39;auth.basic&#39; => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    &#39;guest&#39; => \App\Http\Middleware\RedirectIfAuthenticated::class,
    &#39;throttle&#39; => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  &#39;mymiddleware&#39;=>\App\Http\Middleware\MyMiddleware::class,
  ];
}
Copy after login

It is clear at a glance that the middleware array is defined in HttpKernel.

After what needs to be done, the process from request to response begins, see index.php

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

Finally, abort and release all resource.

/**
* Call the terminate method on any terminable middleware.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response $response
* @return void
*/
public function terminate($request, $response)
{
    $this->terminateMiddleware($request, $response);
    $this->app->terminate();
}
Copy after login

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

1.index.php loading\ bootstrap\app.php, create the Container in the constructor of the Application class, register the ServiceProvider, define the alias array, and then use the app variable to save the object constructed by the constructor.

2. Use the app object to create a singleton mode object HttpKernel. When creating HttpKernel, the constructor is called to complete the declaration of the middleware.

3. The above work is completed before requesting a visit. Next, we start waiting for the request, and then: Accept the request-->Process the request -->Send response-->Stop app variable

The above is the entire content of this article, I hope it will be helpful to everyone's learning, more related Please pay attention to the PHP Chinese website for content!

Related recommendations:

Laravel framework implements the use of middleware for operation logging function

Laravel framework implements the use of listeners for sql statements Record function

Laravel framework’s routing settings

The above is the detailed content of Analysis of the life cycle and principles of the Laravel framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!