搜索
首页后端开发php教程对于Laravel框架的生命周期与原理分析
对于Laravel框架的生命周期与原理分析Jun 12, 2018 pm 04:42 PM
laravel框架生命周期

这篇文章主要介绍了Laravel框架生命周期与原理,结合实例形式总结分析了Laravel框架针对用户请求响应的完整运行周期、流程、原理,需要的朋友可以参考下

本文实例讲述了Laravel框架生命周期与原理。分享给大家供大家参考,具体如下:

引言:

如果你对一件工具的使用原理了如指掌,那么你在用这件工具的时候会充满信心!

正文:

一旦用户(浏览器)发送了一个HTTP请求,我们的apache或者nginx一般都转到index.php,因此,之后的一系列步骤都是从index.php开始的,我们先来看一看这个文件代码。

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

作者在注释里谈了kernel的作用,kernel的作用,kernel处理来访的请求,并且发送相应返回给用户浏览器。

这里又涉及到了一个app对象,所以附上app对象,所以附上app对象的源码,这份源码是\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;

请看app变量是Illuminate\Foundation\Application类的对象,所以调用了这个类的构造函数,具体做了什么事,我们看源码。

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

构造器做了3件事,前两件事很好理解,创建Container,注册了ServiceProvider,看代码

/**
 * 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));
}

最后一件事,是做了个很大的数组,定义了大量的别名,侧面体现程序员是聪明的懒人。

/**
 * 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);
    }
  }
}

这里出现了一个instance函数,其实这并不是Application类的函数,而是Application类的父类Container类的函数

/**
 * 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);
  }
}

Application是Container的子类,所以$app不仅是Application类的对象,还是Container的对象,所以,新出现的singleton函数我们就可以到Container类的源代码文件里查。bind函数和singleton的区别见这篇博文。

singleton这个函数,前一个参数是实际类名,后一个参数是类的“别名”。

$app对象声明了3个单例模型对象,分别是HttpKernelConsoleKernelExceptionHandler。请注意,这里并没有创建对象,只是声明,也只是起了一个“别名”

大家有没有发现,index.php中也有一个$kernel变量,但是只保存了make出来的HttpKernel变量,因此本文不再讨论,ConsoleKernel,ExceptionHandler。。。

继续在文件夹下找到App\Http\Kernel.php,既然我们把实际的HttpKernel做的事情都写在这个php文件里,就从这份代码里看看究竟做了哪些事?

<?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,
  ];
}

一目了然,HttpKernel里定义了中间件数组。

该做的做完了,就开始了请求到响应的过程,见index.php

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

最后在中止,释放所有资源。

/**
* 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();
}

总结一下,简单归纳整个过程就是:

1.index.php加载\bootstrap\app.php,在Application类的构造函数中创建Container,注册了ServiceProvider,定义了别名数组,然后用app变量保存构造函数构造出来的对象。

2.使用app这个对象,创建1个单例模式的对象HttpKernel,在创建HttpKernel时调用了构造函数,完成了中间件的声明。

3.以上这些工作都是在请求来访之前完成的,接下来开始等待请求,然后就是:接受到请求-->处理请求-->发送响应-->中止app变量

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Laravel框架实现利用中间件进行操作日志记录功能

Laravel框架实现利用监听器进行sql语句记录功能

Laravel框架的路由设置

以上是对于Laravel框架的生命周期与原理分析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
vue3改了几个生命周期函数vue3改了几个生命周期函数Jan 13, 2023 pm 05:57 PM

vue3改了4个生命周期函数。Vue3组合式api取消了beforeCreated和created钩子函数,采用steup钩子代替,且里面不能使用this。Vue3里面的组件销毁的钩子函数由destroyed和beforeDestroy换成了beforeUnmount和unmounted。

如何处理 C++ 函数指针的析构和生命周期管理?如何处理 C++ 函数指针的析构和生命周期管理?Apr 17, 2024 pm 05:48 PM

在C++中,函数指针需要适当的析构和生命周期管理。可以通过以下方式实现:手动析构函数指针,释放内存。使用智能指针,如std::unique_ptr或std::shared_ptr,自动管理函数指针的生命周期。将函数指针绑定到对象,对象生命周期管理函数指针的析构。在GUI编程中,使用智能指针或绑定到对象可确保回调函数在适当的时候被析构,避免内存泄漏和不一致。

servlet生命周期分几个阶段servlet生命周期分几个阶段Feb 23, 2023 pm 01:46 PM

Servlet生命周期是指servlet从创建直到毁灭的整个过程,可分为3个阶段:1、初始化阶段,调用init()方法实现Servlet的初始化工作;2、运行阶段(处理请求),容器会为指定请求创建代表HTTP请求的ServletRequest对象和代表HTTP响应的ServletResponse对象,然后将它们作为参数传递给Servlet的service()方法;3、销毁阶段。

如何在Laravel框架中使用模型事件(Model Events)如何在Laravel框架中使用模型事件(Model Events)Jul 28, 2023 am 10:49 AM

如何在Laravel框架中使用模型事件(ModelEvents)Laravel框架提供了许多强大的功能,其中之一是模型事件(ModelEvents)。模型事件是在Laravel的EloquentORM(对象关系映射)中使用的一种功能,它允许开发人员在模型发生特定动作时执行自定义的代码。在本文中,我们将探讨如何在Laravel框架中使用模型事件,并提供一

Vue3中的生命周期函数:快速掌握Vue3的生命周期Vue3中的生命周期函数:快速掌握Vue3的生命周期Jun 18, 2023 am 08:20 AM

Vue3是目前前端界最热门的框架之一,而Vue3的生命周期函数是Vue3中非常重要的一部分。Vue3的生命周期函数可以让我们实现在特定的时机触发特定的事件,增强了组件的高度可控性。本文将从Vue3的生命周期函数的基本概念、各个生命周期函数的作用和使用方法以及实现案例等方面进行详细探究和讲解,帮助读者快速掌握Vue3的生命周期函数。一、Vue3的生命周期函数的

vue3的生命周期有哪些vue3的生命周期有哪些Feb 01, 2024 pm 04:33 PM

vue3的生命周期:1、beforeCreate;2、created;3、beforeMount;4、mounted;5、beforeUpdate;6、updated;7、beforeDestroy;8、destroyed;9、activated;10、deactivated;11、errorCaptured;12、getDerivedStateFromProps等等

如何控制 Golang 协程的生命周期?如何控制 Golang 协程的生命周期?May 31, 2024 pm 06:05 PM

控制Go协程的生命周期可以通过以下方式:创建协程:使用go关键字启动新任务。终止协程:等待所有协程完成,使用sync.WaitGroup。使用通道关闭信号。使用上下文context.Context。

Go语言中的变量作用域与生命周期Go语言中的变量作用域与生命周期Jun 01, 2023 pm 12:31 PM

Go语言是一种开源的静态类型语言,它具有简洁、高效、可靠等特点,越来越受到开发者的喜爱。在Go语言中,变量是程序中最基本的数据存储形式,变量的作用域和生命周期对于程序的正确性和效率十分重要。变量的作用域指的是变量的可见性和可访问性,即在何处可以访问这个变量。在Go语言中,变量的作用域分为全局变量和局部变量。全局变量是定义在函数外部的变量,它可以被整个程序任何

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境