侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Laravel框架生命周期与原理分析

Laravel  /  管理员 发布于 5年前   396

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

引言:

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

正文:

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

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

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

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

/** * Register the core class aliases in the container. * * @return void */public function registerCoreContainerAliases(){  $aliases = [    'app'         => [\Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class],    'auth'         => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],    'auth.driver'     => [\Illuminate\Contracts\Auth\Guard::class],    'blade.compiler'    => [\Illuminate\View\Compilers\BladeCompiler::class],    'cache'        => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class],    'cache.store'     => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::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::class],    '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\FilesystemManager::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\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class],    'log'         => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::class, \Psr\Log\LoggerInterface::class],    'mailer'        => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\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\Factory::class, \Illuminate\Contracts\Queue\Monitor::class],    'queue.connection'   => [\Illuminate\Contracts\Queue\Queue::class],    'queue.failer'     => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],    'redirect'       => [\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\Router::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::class, \Illuminate\Contracts\Routing\UrlGenerator::class],    'validator'      => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class],    'view'         => [\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'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个单例模型对象,分别是HttpKernel,ConsoleKernel,ExceptionHandler。请注意,这里并没有创建对象,只是声明,也只是起了一个“别名”。

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

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

 [      \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 be assigned to groups or used individually.   *   * @var array   */  protected $routeMiddleware = [    'auth' => \App\Http\Middleware\Authenticate::class,    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,  'mymiddleware'=>\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变量

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • Laravel6.2中用于用户登录的新密码确认流程详解
  • Laravel 5框架学习之模型、控制器、视图基础流程
  • Laravel 5.4重新登录实现跳转到登录前页面的原理和方法
  • Laravel中间件实现原理详解
  • Laravel模型事件的实现原理详解
  • 浅谈Laravel队列实现原理解决问题记录
  • Laravel框架队列原理与用法分析
  • Laravel认证原理以及完全自定义认证详解
  • laravel框架模型中非静态方法也能静态调用的原理分析
  • 浅谈laravel aliases别名的原理
  • laravel 框架执行流程与原理简单分析


  • 上一条:
    Laravel框架路由设置与使用示例
    下一条:
    Laravel框架分页实现方法分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • Laravel 11.14版本发布 - 新的字符串助手和ServeCommand改进(0个评论)
    • Laravel 11.12版本发布 - Artisan的`make`命令自动剪切`.php `扩展(0个评论)
    • Laravel的轻量型购物车扩展包:binafy/laravel-cart(0个评论)
    • Laravel 11.11版本发布 - 查看模型中的第三方关系:show(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客