您好,欢迎访问一九零五行业门户网

一起来聊聊Laravel的生命周期

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于laravel的生命周期相关问题,laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。
【相关推荐:laravel视频教程】
laravel的生命周期 a世间万物皆有生命周期,当我们使用任何工具时都需要理解它的工作原理,那么用起来就会得心应手,应用开发也是如此。理解了它的原理,那么使用起来就会游刃有余。
在了解 laravel 的生命周期前,我们先回顾一下php 的生命周期。
php 的运行模式php两种运行模式是web模式、cli模式。
当我们在终端敲入php这个命令的时候,使用的是cli模式。
当使用nginx或者别web服务器作为宿主处理一个到来的请求时,使用的是web模式。
php 的生命周期当我们请求一个php文件时,php 为了完成这次请求,会发生5个阶段的生命周期切换:
1 模块初始化(minit),即调用 php.ini 中指明的扩展的初始化函数进行初始化工作,如 mysql 扩展。
2 请求初始化(rinit),即初始化为执行本次脚本所需要的变量名称和变量值内容的符号表,如 $_session变量。
3 执行该php脚本。
4 请求处理完成(request shutdown),按顺序调用各个模块的 rshutdown 方法,对每个变量调用 unset 函数,如 unset $_session 变量。
5 关闭模块(module shutdown) , php调用每个扩展的 mshutdown 方法,这是各个模块最后一次释放内存的机会。这意味着没有下一个请求了。
web模式和cli(命令行)模式很相似,区别是:
cli 模式会在每次脚本执行经历完整的5个周期,因为你脚本执行完不会有下一个请求;
web模式为了应对并发,可能采用多线程,因此生命周期1和5有可能只执行一次,下次请求到来时重复2-4的生命周期,这样就节省了系统模块初始化所带来的开销。
可以看出php生命周期是很对称的。说了这么多,就是为了定位laravel运行在哪里,没错,laravel仅仅运行再 第三个阶段:
作用理解这些,你就可以优化你的 laravel 代码,可以更加深入的了解 laravel 的singleton(单例)。
至少你知道了,每一次请求结束,php 的变量都会 unset,laravel 的 singleton 只是在某一次请求过程中的singleton;
你在 laravel 中的静态变量也不能在多个请求之间共享,因为每一次请求结束都会 unset。
理解这些概念,是写高质量代码的第一步,也是最关键的一步。因此记住,php是一种脚本语言,所有的变量只会在这一次请求中生效,下次请求之时已被重置,而不像java静态变量拥有全局作用。
laravel 的生命周期概述
laravel 的生命周期从public\index.php开始,从public\index.php结束。
请求过程下面是 public\index.php的全部源码,更具体来说可以分为四步:
f5d12ef5374bbdf3fe12fa9f5a99535amake(illuminate\contracts\http\kernel::class);$response = $kernel->handle(    $request = illuminate\http\request::capture());$response->send();$kernel->terminate($request, $response);
以下是四步详细的解释是:composer自动加载需要的类
1 文件载入composer生成的自动加载设置,包括所有你 composer require的依赖。2 生成容器 container,application实例,并向容器注册核心组件(httpkernel,consolekernel ,exceptionhandler)(对应代码2,容器很重要,后面详细讲解)。3 处理请求,生成并发送响应(对应代码3,毫不夸张的说,你99%的代码都运行在这个小小的handle 方法里面)。4 请求结束,进行回调(对应代码4,还记得可终止中间件吗?没错,就是在这里回调的)。
laravel 的请求步骤第一步:注册加载composer自动生成的class loader
就是加载初始化第三方依赖。
第二步:生成容器 container
并向容器注册核心组件,是从 bootstrap/app.php 脚本获取 laravel 应用实例,
第三步:这一步是重点,处理请求,并生成发送响应。
请求被发送到 http 内核或 console 内核,这取决于进入应用的请求类型。
取决于是通过浏览器请求还是通过控制台请求。这里我们主要是通过浏览器请求。
http 内核继承自 illuminate\foundation\http\kernel 类,该类定义了一个 bootstrappers 数组,这个数组中的类在请求被执行前运行,这些 bootstrappers 配置了错误处理、日志、检测应用环境以及其它在请求被处理前需要执行的任务。
protected $bootstrappers = [        //注册系统环境配置 (.env)        'illuminate\foundation\bootstrap\detectenvironment',        //注册系统配置(config)        'illuminate\foundation\bootstrap\loadconfiguration',        //注册日志配置        'illuminate\foundation\bootstrap\configurelogging',        //注册异常处理        'illuminate\foundation\bootstrap\handleexceptions',        //注册服务容器的门面,facade 是个提供从容器访问对象的类。        'illuminate\foundation\bootstrap\registerfacades',        //注册服务提供者        'illuminate\foundation\bootstrap\registerproviders',        //注册服务提供者 `boot`        'illuminate\foundation\bootstrap\bootproviders',    ];
laravel的生命周期 b
laravel/public/index.php/** * laravel的启动时间 */define('laravel_start', microtime(true));/** * 加载项目依赖。 * 现代php依赖于composer包管理器,入口文件通过引入由composer包管理器。 * 自动生成的类加载程序,可以轻松注册并加载所依赖的第三方组件库。 */require __dir__.'/../vendor/autoload.php';/** * 创建laravel应用实例。 */$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);
laravel/boostrap/app.php# 第一部分:创建应用实例$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;
laravel\vendor\laravel\framework\src\illuminate\foundation\http\kernel.phpclass kernel implements kernelcontract{    protected $bootstrappers = [        \illuminate\foundation\bootstrap\loadenvironmentvariables::class, // 注册系统环境配置        \illuminate\foundation\bootstrap\loadconfiguration::class,              // 注册系统配置         \illuminate\foundation\bootstrap\handleexceptions::class,              // 注册异常注册        \illuminate\foundation\bootstrap\registerfacades::class,                // 注册门面模式        \illuminate\foundation\bootstrap\registerproviders::class,              // 注册服务提供者         \illuminate\foundation\bootstrap\bootproviders::class,                    // 注册服务提供者boot    ];    // 处理请求    public function handle($request)    {        try {            $request->enablehttpmethodparameteroverride();            $response = $this->sendrequestthroughrouter($request);        } catch (exception $e) {            $this->reportexception($e);            $response = $this->renderexception($request, $e);        } catch (throwable $e) {            $this->reportexception($e = new fatalthrowableerror($e));            $response = $this->renderexception($request, $e);        }        $this->app['events']->dispatch(            new events\requesthandled($request, $response)        );        return $response;    }    protected function sendrequestthroughrouter($request)    {        # 一、将$request实例注册到app容器        $this->app->instance('request', $request);        # 二、清除之前的$request实例缓存        facade::clearresolvedinstance('request');        # 三、启动引导程序        $this->bootstrap();        # 四、发送请求        return (new pipeline($this->app)) //创建管道                    ->send($request)      //发送请求                    ->through($this->app->shouldskipmiddleware() ? [] : $this->middleware)  //通过中间件                    ->then($this->dispatchtorouter());  //分发到路由    }    # 启动引导程序    public function bootstrap()    {        if (! $this->app->hasbeenbootstrapped()) {            $this->app->bootstrapwith($this->bootstrappers());        }    }        # 路由分发    protected function dispatchtorouter()    {        return function ($request) {            $this->app->instance('request', $request);            return $this->router->dispatch($request);        };    }    #  终止程序    public function terminate($request, $response)    {        $this->terminatemiddleware($request, $response);        $this->app->terminate();    }
laravel 服务容器模块简介服务容器是一个用于管理类依赖和执行依赖注入的强大工具。是整个框架的核心;
几乎所有的服务容器绑定都是在服务提供者中完成。
框架调用分析在框架直接生成服务容器的只有一处,在bootstrap/app.php,通过require引用会返回服务容器实例。通过require引用有两处,一处是public/index.php,服务器访问的入口;另一处是tests/createsapplication.php,是单元测试的入口;
如果想在项目各处中调用,可以调用$app = illuminate\container\container::getinstance()或者全局帮助函数app()获取服务容器实例(也就是illuminate\foundation/application实例);
illuminate\foundation/application是对illuminate\container\container的又一层封装;
application初始化那么实例化illuminate\foundation/application时,做了什么呢?
第一步,设置应用的根目录,并同时注册核心目录到服务容器中;核心的目录有以下
path:目录app的位置
path.base:项目根目录的位置
path.lang:目录resources/lang的位置
path.config:目录config的位置
path.public:目录public的位置
path.storage:目录storage的位置
path.database:目录database的位置
path.resources:目录resources的位置
path.bootstrap:目录bootstrap的位置
第二步,将当前illuminate\foundation/application实例保存到$instance类变量,并同时绑定到服务容器作单例绑定,绑定名为app或container::class;
第三步,顺序分别执行注册illuminate\events\eventserviceprovider、illuminate\log\logserviceprovider和illuminate\routing\routingserviceprovider三个服务提供者;
注册服务提供者的顺序如下:
如果类变量$serviceproviders已经存在该服务提供者并且不需要强制重新注册,则返回服务提供者实例$provider;
未注册过当前服务提供者,则继续执行以下;
如果存在register方法,执行服务提供者的register方法;
将当前服务提供者$provider实例保存到类变量$serviceproviders数组中,同时标记类变量$loadedproviders[get_class($provider)]的值为true;
判断类变量$booted是否为true,如果是true,则执行服务提供者的boot方法;(类变量$booted应该是标志是否所有服务提供者均注册,框架是否启动)
第四步,注册核心类别名;
比如\illuminate\foundation\application::class、\illuminate\contracts\container\container::class起别名为app;
单元测试application的bootstrap启动分析启动代码很简洁,
route::get('dev', 'dev@index');public function index(){     // require 初始化分析上面已经介绍了    $app = require base_path('bootstrap/app.php');    $kernel = $app->make('illuminate\contracts\http\kernel');        dd($kernel);}
构造函数主要干了一件事,注册一个booted完成后的回调函数,函数执行的内容为“注册 schedule实例到服务提供者,同时加载用户定义的schedule任务清单”;
bootstrap方法的执行内容如下:
加载illuminate/foundation/console/kernel中$bootstrappers变量数组中的类,执行它们的bootstrap方法;
protected $bootstrappers = [ // 加载 .env 文件 \illuminate\foundation\bootstrap\loadenvironmentvariables::class, // 加载 config 目录下的配置文件 \illuminate\foundation\bootstrap\loadconfiguration::class, // 自定义错误报告,错误处理方法及呈现 \illuminate\foundation\bootstrap\handleexceptions::class, // 为 config/app.php 中的 aliases 数组注册类别名 \illuminate\foundation\bootstrap\registerfacades::class, // 在服务容器中单例绑定一个 request 对象,控制台命令会用到 \illuminate\foundation\bootstrap\setrequestforconsole::class, // 注册 config\app.php 中的 providers 服务提供者 \illuminate\foundation\bootstrap\registerproviders::class, // 项目启动,执行每个 serviceprovider 的 boot 方法, \illuminate\foundation\bootstrap\bootproviders::class,];
加载延迟的服务提供者;
http访问application的bootstrap启动分析启动入口文件在public\index.php
$app = require_once __dir__.'/../bootstrap/app.php';// 实例化 illuminate/foundation/http/kernel 对象$kernel = $app->make(illuminate\contracts\http\kernel::class);// 中间件处理、业务逻辑处理$response = $kernel->handle( // 根据 symfony 的 request 对象封装出 illuminate\http\request $request = illuminate\http\request::capture() );$response->send();// 执行所有中间件的 terminate 方法,执行 application 中的 terminatingcallbacks 回调函数$kernel->terminate($request, $response);
重要的类变量数组aliases数组维护 类与别名 的数组;键名为 类的全限定类名,键值为 数组,每一个元素都是该类的别名;
判断指定类是否有别名:app()->isalias($name);
获取指定类的别名:app()->getalias($abstract);
abstractaliases数组维护 类与别名 的数组;键名为 别名,键值为 类的全限定类名;
instances数组维护 类与实例的数组;键名为 类的全限定类名,键值为该类的实例;
移除绑定类:app()->forgetinstance($abstract);
移除所有绑定类:app()->forgetinstances();
bindings数组通过 bind 方法实现 接口类与实现的绑定;
获取bindings数组中的内容:app()->getbindings()
resolved数组键名为 类的全限定类名,键值为布尔值类型(true表示已解析过,false表示未解析过);
with 数组在resolved过程中,会有一些参数;with数组就是参数栈,开始解析时将参数入栈,结束解析时参数出栈;
contextual数组上下文绑定数组;第一维数组键名为 场合类(比如某个controller类的类名),第二维数组键名为 抽象类(需要实现的接口类),键值为 closure 或 某个具体类的类名;
tags数组维护 标签与类 的数组;键名是 标签名,键值是 对应要绑定的类的名称;
如果调用tagged方法,会将键值数组中的类都make出来,并以数组形式返回;
extenders数组在make或resolve出对象的时候,会执行
foreach ($this->getextenders($abstract) as $extender) { $object = $extender($object, $this);}
能对解析出来的对象进行修饰;
methodbindings数组向容器绑定方法与及实现:app()->bindmethod($method, $callback)
判断容器内是否有指定方法的实现:app()->hasmethodbinding($method)
执行方法的实现:app()->callmethodbinding($method, $instance)或者app()->call($method)
buildstack数组调用build方法时维护的栈,栈中存放的是当前要new的类名;
reboundcallbacks数组当调用rebound函数时,会触发rebound中为此$abstract设置的回调函数;
注册入口:app()->rebinding($abstract, closure $callback);
serviceproviders数组已在系统注册的服务提供者serviceprovider;
数组内存放的是loadedproviders键名对应类的实例;
loadedproviders数组系统已加载的serviceprovider的集合;键名为serviceprovider的全限定类名,键值为布尔值(true表示已加载,false表示未加载);
获取延迟加载对象:app()->getloadedproviders();
deferredservices数组有些服务提供者是会延迟加载的;这时候会将这些服务提供者声明的服务登录在deferredservices数组,键名为延迟加载对象名 ,键值为该延迟加载对象所在的serviceprovider;
获取延迟加载对象:app()->getdeferredservices();
bootingcallbacks数组项目启动前执行的回调函数;(项目启动是在执行\illuminate\foundation\bootstrap\bootproviders::class的时候)
注册入口:app()->booting($callback);
bootedcallbacks数组项目启动后执行的回调函数;(项目启动是在执行\illuminate\foundation\bootstrap\bootproviders::class的时候)
注册入口:app()->booted($callback);
resolvingcallbacks数组解析时回调函数集合;键名为 类名, 键值为 回调函数数组,每一个元素都是回调函数;
注册入口:app()->resolving($abstract, $callback);
afterresolvingcallbacks数组解析后回调函数集合;键名为 类名, 键值为 回调函数数组,每一个元素都是回调函数;
注册入口:app()->afterresolving($abstract, $callback);
globalresolvingcallbacks数组全局解析时回调函数集合;每一次resolve方法调用时都会执行的回调函数集合;
注册入口:app()->resolving($callback);
globalafterresolvingcallbacks数组全局解析后回调函数集合;每一次resolve方法调用后都会执行的回调函数集合;
注册入口:app()->afterresolving($callback);
terminatingcallbacks数组系统在返回response之后,会执行terminate方法,来做应用结束前的扫尾处理;
这个数组就是执行terminate方法时会执行的回调函数集合;
注册入口:app()->terminating(closure $callback);
常用方法的解析bind方法public function bind($abstract, $concrete = null, $shared = false)
第一个参数是要注册的类名或接口名,第二个参数是返回类的实例的闭包(或类的实例类名),第三个参数是否是单例;
方法内部流程:
unset 掉 instances 和 aliases 数组中键值为 $abstract 的元素;
如果 $concrete 值为 null ,将 $abstract 赋值给 $concrete;
如果 $concrete 不是 closure 对象,则封装成闭包;
将 $concrete 和 $shared 通过 compact,添加进 bindings 数组,键名为 $abstract;
判断 $abstract 在 resolved 和 instances 数组中是否存在,如果存在,则执行第 6 步;
触发 rebound回调函数;如果 reboundcallbacks 数组中注册以 $abstract 为键名的回调函数,则执行这些回调函数;
涉及数组:instances和aliases(unset 操作)、bindings(add 操作)
singleton方法单例绑定;
public function singleton($abstract, $concrete = null) $this->bind($abstract, $concrete, true);}
涉及数组:instances和aliases(unset 操作)、bindings(add 操作)
bindif方法单例绑定;
public function bindif($abstract, $concrete = null, $shared = false) { if (! $this->bound($abstract)) { $this->bind($abstract, $concrete, $shared); }}
涉及数组:instances和aliases(unset 操作)、bindings(add 操作)
instance方法绑定实例;
public function instance($abstract, $instance)
方法内部流程:
如果$abstract在aliases数组中存在,则从abstractaliases中所有的值数组中移除该类;
unset 掉 aliases 数组中键名为 $abstract的元素;
赋值操作:$this->instances[$abstract] = $instance;
判断 $abstract 在 resolved 和 instances 数组中是否存在,如果存在,则执行第 5 步;
触发 rebound回调函数;如果 reboundcallbacks 数组中注册以 $abstract 为键名的回调函数,则执行这些回调函数;
涉及数组:instances(add 操作)、aliases 和 abstractaliases(unset 操作)
make方法public function make($abstract) { return $this->resolve($abstract);}
alias给类起别名;
public function alias($abstract, $alias) { $this->aliases[$alias] = $abstract; $this->abstractaliases[$abstract][] = $alias;}
涉及数组:aliases和abstractaliases(add 操作)
laravel 的源代码生命周期 第一步 laravel 应用的所有请求入口都是 public/index.php 文件。打开 index.php 发现代码也就几行。
下面我们来讲一下每一句代码的作用是什么?
// 定义了laravel一个请求的开始时间define('laravel_start', microtime(true));// composer自动加载机制require __dir__.'/../vendor/autoload.php';// 这句话你就可以理解laravel,在最开始引入了一个ioc容器。$app = require_once __dir__.'/../bootstrap/app.php';// 打开__dir__.'/../bootstrap/app.php';你会发现这段代码,绑定了illuminate\contracts\http\kernel::class,// 这个你可以理解成之前我们所说的$ioc->bind();方法。// $app->singleton(// illuminate\contracts\http\kernel::class,// app\http\kernel::class// );// 这个相当于我们创建了kernel::class的服务提供者$kernel = $app->make(illuminate\contracts\http\kernel::class);// 获取一个 request ,返回一个 response。以把该内核想象作一个代表整个应用的大黑盒子,输入 http 请求,返回 http 响应。$response = $kernel->handle( $request = illuminate\http\request::capture());// 就是把我们服务器的结果返回给浏览器。$response->send(); // 这个就是执行我们比较耗时的请求,$kernel->terminate($request, $response);
走到这里你会发现,是不是在我们学会了 ioc,服务提供者理解起来就比较简单了。那 $middleware,服务提供者都是在哪个文件注册运行的呢?
打开 app\http\kernel::class 这个文件,你会发现定义了一堆需要加载的 $middleware。这个 kernel 的主要方法还是在他的父类里面 illuminate\foundation\http\kernel 中。
打开 illuminate\foundation\http\kernel,你会发现定义了启动时需要做的事呢?
protected $bootstrappers = [ \illuminate\foundation\bootstrap\loadenvironmentvariables::class, \illuminate\foundation\bootstrap\loadconfiguration::class, \illuminate\foundation\bootstrap\handleexceptions::class, \illuminate\foundation\bootstrap\registerfacades::class, \illuminate\foundation\bootstrap\registerproviders::class, \illuminate\foundation\bootstrap\bootproviders::class,];
$bootstrappers 就定义了我们的 registerfacades.class,registerproviders.class 这两个类的意思就是要将我们在 app.config 中的 providers,facades 注入到我们的 ioc 容器中。
【相关推荐:laravel视频教程】
以上就是一起来聊聊laravel的生命周期的详细内容。
其它类似信息

推荐信息