Heim  >  Artikel  >  PHP-Framework  >  Analyse des Startvorgangs des Laravel-Frameworks

Analyse des Startvorgangs des Laravel-Frameworks

不言
不言Original
2018-07-31 11:18:593016Durchsuche

Für diejenigen, die gerade das Laravel-Framework gelernt haben, ist der Startvorgang des Laravel-Frameworks möglicherweise etwas schwierig zu verstehen. Der Startvorgang des Laravel-Frameworks ist auch der Kerninhalt von Laravel Lassen Sie alle diesen Prozess verstehen, damit sie dieses Framework in Zukunft schneller nutzen können.

Tipps: Bevor Sie dies tun, lesen Sie am besten die offizielle Dokumentation, kennen Sie wahrscheinlich Laravel und lesen Sie dann diesen Hinweis. Der Effekt ist möglicherweise besser.

统一入口

laravel框架使用了统一入口,入口文件:/public/index.php

<?php
//自动加载文件设置
require __DIR__.&#39;/../bootstrap/autoload.php&#39;;
//初始化服务容器(可以查看一下关于‘服务容器’的相关文档)
$app = require_once __DIR__.&#39;/../bootstrap/app.php&#39;;
//通过服务容器生成一个kernel类的实例(Illuminate\Contracts\Http\Kernel实际上只是一个接口,真正生成的实例是App\Http\Kernel类,至于怎么把接口和类关联起来,请查看Contracts相关文档)
$kernel = $app->make(&#39;Illuminate\Contracts\Http\Kernel&#39;);
//运行Kernel类的handle方法,主要动作是运行middleware和启动URL相关的Contrller
$response = $kernel->handle(    
$request = Illuminate\Http\Request::capture()
);
//控制器返回结果之后的操作,暂时还没看,以后补上
$response->send();
$kernel->terminate($request, $response);
自动加载文件

laravel的自动加载,其实也就是Composer的自动加载

我的理解是,Composer根据声明的依赖关系,从相关库的源下载代码文件,并根据依赖关系在 Composer 目录下生成供类自动加载的 PHP 脚本,使用的时候,项目开始处引入 “/vendor/autoload.php” 文件,就可以直接实例化这些第三方类库中的类了。那么,Composer 是如何实现类的自动加载的呢?接下来,我们从 laravel 的入口文件开始顺藤摸瓜往里跟进,来一睹 Composer 自动加载的奥妙。

代码清单/bootstrap/autoload.php

<?php
define(&#39;LARAVEL_START&#39;, microtime(true));
//这就是传说中Composer的自动加载文件
require __DIR__.&#39;/../vendor/autoload.php&#39;;
//Composer自动生成的各个核心类的集合,如果你需要修改一些vendor里面的文件来查看一些laravel运行细节,那么就请删除此文件
$compiledPath = __DIR__.&#39;/../vendor/compiled.php&#39;;
if (file_exists($compiledPath))
{    
require $compiledPath;
}

代码清单 laravel/vendor/autoload.php

<?php
// autoload.php @generated by Composer
require_once __DIR__ . &#39;/composer&#39; . &#39;/autoload_real.php&#39;;
//别被吓到了,他就是autoload_real.php文件的类名而已
return ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01::getLoader();

代码清单laravel/vendor/composer/autoload_real.php:
主要是getLoader方法里面,加了注释的几行,这是关键

<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01{    
private static $loader;    
public static function loadClassLoader($class)
    {        
    if (&#39;Composer\Autoload\ClassLoader&#39; === $class)
     {            
     require __DIR__ . &#39;/ClassLoader.php&#39;;
        }
    }    
    public static function getLoader()
    {        
    if (null !== self::$loader) {            
    return self::$loader;
        }

        spl_autoload_register(array(&#39;ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01&#39;, &#39;loadClassLoader&#39;), true, true);        
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array(&#39;ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01&#39;, &#39;loadClassLoader&#39;));        
        $includePaths = require __DIR__ . &#39;/include_paths.php&#39;;
        array_push($includePaths, get_include_path());
        set_include_path(join(PATH_SEPARATOR, $includePaths));        
        //Psr0标准-设置命名空间对应的路径,以便于随后自动加载相关类文件(看看psr0和psr4的区别)
        $map = require __DIR__ . &#39;/autoload_namespaces.php&#39;;        
        foreach ($map as $namespace => $path) {            
        $loader->set($namespace, $path);
        }        
        //Psr4标准-设置命名空间对应的路径,以便于随后自动加载相关类文件(看看psr0和psr4的区别)
        $map = require __DIR__ . &#39;/autoload_psr4.php&#39;;        
        foreach ($map as $namespace => $path) {            
        $loader->setPsr4($namespace, $path);
        }        
        //设置类文件路径与类名的对应关系,以便于随后自动加载相关类文件(可能你有一部分类,由于历史原因,他们的命名空间不遵守PSR0和PSR4,你就可以使用此方法自动加载)
        $classMap = require __DIR__ . &#39;/autoload_classmap.php&#39;;        
        if ($classMap) {            
        $loader->addClassMap($classMap);
        }        
        //根据上述三种方法注册自动加载文档的方法,可以查看一下PHP的spl_autoload_register和__autoload方法
        $loader->register(true);        
        //加载公用方法,比如app()方法取得一个application实例,就是这里加载的,可以查看一下autoload_files.php文件都加载了什么公用方法,有很多关于 array的操作方法哦
        $includeFiles = require __DIR__ . &#39;/autoload_files.php&#39;;        
        foreach ($includeFiles as $file) {
            composerRequire03dc6c3c47809c398817ca33ec5f6a01($file);
        }        
        return $loader;
    }
}
function composerRequire03dc6c3c47809c398817ca33ec5f6a01($file){    
require $file;
}
对于laravel自动加载过程的总结

laravel自动加载的过程就是这样实现的,总结为四种加载方式:

  1. PSR0加载方式—对应的文件就是autoload_namespaces.php

  2. PSR4加载方式—对应的文件就是autoload_psr4.php

  3. 其他加载类的方式—对应的文件就是autoload_classmap.php

  4. 加载公用方法—对应的文件就是autoload_files.php

怎么样自定义自动加载方式

如果某些文件,需要自动自定义加载方式,可以在Composer.json文件中定义

"autoload" : {        
//以第一种方式自动加载,表示app目录下的所有类的命名空间都是以Apppsr0开始且遵循psr0规范(注意:您的laravel中没有此项,作为示意例子)
        "psr-0" : {            
        "AppPsr0": "apppsr0/"
        },        
        //以第二种方式自动加载,表示app目录下的所有类的命名空间都是以App开始且遵循psr4规范
        "psr-4" : {            
        "App\\": "app/"
        },        
        //以第三种加载方式自动加载,它会将所有.php和.inc文件中的类提出出来然后以类名作为key,类的路径作为值
        "classmap" : ["database"],        
        //以第四种加载方式自动加载,composer会把这些文件都include进来(注意:您的laravel中没有此项,作为示意例子)
        "files" : ["common/util.php"]

    }

服务容器——laravel真正的核心

服务容器,也叫IOC容器,其实包含了依赖注入(DI)和控制反转(IOC)两部分,是laravel的真正核心。其他的各种功能模块比如 Route(路由)、Eloquent ORM(数据库 ORM 组件)、Request and Response(请求和响应)等等等等,实际上都是与核心无关的类模块提供的,这些类从注册到实例化,最终被你所使用,其实都是 laravel 的服务容器负责的。服务容器这个概念比较难解释清楚,只能一步步从服务容器的产生历史慢慢解释

IoC 容器诞生的故事——石器时代(原始模式)

我们把一个“超人”作为一个类,

class Superman {}

我们可以想象,一个超人诞生的时候肯定拥有至少一个超能力,这个超能力也可以抽象为一个对象,为这个对象定义一个描述他的类吧。一个超能力肯定有多种属性、(操作)方法,这个尽情的想象,但是目前我们先大致定义一个只有属性的“超能力”,至于能干啥,我们以后再丰富:

class Power {    
        /**
     * 能力值
     */
    protected $ability;    
    /**
     * 能力范围或距离
     */
    protected $range;    
    public function __construct($ability, $range)
    {        
    $this->ability = $ability;        
    $this->range = $range;
    }
}

这时候我们回过头,修改一下之前的“超人”类,让一个“超人”创建的时候被赋予一个超能力:

class Superman{    
protected $power;    
public function __construct()
    {        
    $this->power = new Power(999, 100);
    }
}

这样的话,当我们创建一个“超人”实例的时候,同时也创建了一个“超能力”的实例,但是,我们看到了一点,“超人”和“超能力”之间不可避免的产生了一个依赖。

所谓“依赖”,就是“我若依赖你,少了你就没有我”。

在一个贯彻面向对象编程的项目中,这样的依赖随处可见。少量的依赖并不会有太过直观的影响,我们随着这个例子逐渐铺开,让大家慢慢意识到,当依赖达到一个量级时,是怎样一番噩梦般的体验。当然,我也会自然而然的讲述如何解决问题。

之前的例子中,超能力类实例化后是一个具体的超能力,但是我们知道,超人的超能力是多元化的,每种超能力的方法、属性都有不小的差异,没法通过一种类描述完全。我们现在进行修改,我们假设超人可以有以下多种超能力:
飞行,属性有:飞行速度、持续飞行时间
蛮力,属性有:力量值
能量弹,属性有:伤害值、射击距离、同时射击个数
我们创建了如下类:

class Flight{    
protected $speed;    
protected $holdtime;    
public function __construct($speed, $holdtime) {}
}
class Force{    
protected $force;    
public function __construct($force) {}
}
class Shot{    
protected $atk;    
protected $range;    
protected $limit;    
public function __construct($atk, $range, $limit) {}
}

好了,这下我们的超人有点“忙”了。在超人初始化的时候,我们会根据需要来实例化其拥有的超能力吗,大致如下:

class Superman{    
protected $power;    
public function __construct()
    {        
    $this->power = new Fight(9, 100);        
    // $this->power = new Force(45);
        // $this->power = new Shot(99, 50, 2);
        /*
        $this->power = array(
            new Force(45),
            new Shot(99, 50, 2)
        );
        */
    }
}

我们需要自己手动的在构造函数内(或者其他方法里)实例化一系列需要的类,这样并不好。可以想象,假如需求变更(不同的怪物横行地球),需要更多的有针对性的 新的 超能力,或者需要 变更 超能力的方法,我们必须 重新改造 超人。换句话说就是,改变超能力的同时,我还得重新制造个超人。效率太低了!新超人还没创造完成世界早已被毁灭。

这时,灵机一动的人想到:为什么不可以这样呢?超人的能力可以被随时更换,只需要添加或者更新一个芯片或者其他装置啥的(想到钢铁侠没)。这样的话就不要整个重新来过了。

IoC 容器诞生的故事——青铜时代(工厂模式)

我们不应该手动在 “超人” 类中固化了他的 “超能力” 初始化的行为,而转由外部负责,由外部创造超能力模组、装置或者芯片等(我们后面统一称为 “模组”),植入超人体内的某一个接口,这个接口是一个既定的,只要这个 “模组” 满足这个接口的装置都可以被超人所利用,可以提升、增加超人的某一种能力。这种由外部负责其依赖需求的行为,我们可以称其为 “控制反转(IoC)”。

工厂模式,顾名思义,就是一个类所以依赖的外部事物的实例,都可以被一个或多个 “工厂” 创建的这样一种开发模式,就是 “工厂模式”。

我们为了给超人制造超能力模组,我们创建了一个工厂,它可以制造各种各样的模组,且仅需要通过一个方法:

class SuperModuleFactory{    
public function makeModule($moduleName, $options)
    {        
    switch ($moduleName) {            
    case &#39;Fight&#39;:     
    return new Fight($options[0], $options[1]);            
    case &#39;Force&#39;:     
    return new Force($options[0]);            
    case &#39;Shot&#39;:     
    return new Shot($options[0], $options[1], $options[2]);
        }
    }
}

这时候,超人 创建之初就可以使用这个工厂!

class Superman{    
protected $power;    
public function __construct()
    {        // 初始化工厂
        $factory = new SuperModuleFactory;        
        // 通过工厂提供的方法制造需要的模块
        $this->power = $factory->makeModule(&#39;Fight&#39;, [9, 100]);        
        // $this->power = $factory->makeModule(&#39;Force&#39;, [45]);
        // $this->power = $factory->makeModule(&#39;Shot&#39;, [99, 50, 2]);
        /*
        $this->power = array(
            $factory->makeModule(&#39;Force&#39;, [45]),
            $factory->makeModule(&#39;Shot&#39;, [99, 50, 2])
        );
        */
    }
}

可以看得出,我们不再需要在超人初始化之初,去初始化许多第三方类,只需初始化一个工厂类,即可满足需求。但这样似乎和以前区别不大,只是没有那么多 new 关键字。其实我们稍微改造一下这个类,你就明白,工厂类的真正意义和价值了。

class Superman{    
protected $power;    
public function __construct(array $modules)
    {        
    // 初始化工厂
        $factory = new SuperModuleFactory;        
        // 通过工厂提供的方法制造需要的模块
        foreach ($modules as $moduleName => $moduleOptions) {            
        $this->power[] = $factory->makeModule($moduleName, $moduleOptions);
        }
    }
}
// 创建超人$superman = new Superman([    
&#39;Fight&#39; => [9, 100], 
    &#39;Shot&#39; => [99, 50, 2]
    ]);

现在修改的结果令人满意。现在,“超人” 的创建不再依赖任何一个 “超能力” 的类,我们如若修改了或者增加了新的超能力,只需要针对修改 SuperModuleFactory 即可。扩充超能力的同时不再需要重新编辑超人的类文件,使得我们变得很轻松。但是,这才刚刚开始。

IoC 容器诞生的故事——铁器时代(依赖注入)

由 “超人” 对 “超能力” 的依赖变成 “超人” 对 “超能力模组工厂” 的依赖后,对付小怪兽们变得更加得心应手。但这也正如你所看到的,依赖并未解除,只是由原来对多个外部的依赖变成了对一个 “工厂” 的依赖。假如工厂出了点麻烦,问题变得就很棘手。

其实大多数情况下,工厂模式已经足够了。工厂模式的缺点就是:接口未知(即没有一个很好的契约模型,关于这个我马上会有解释)、产生对象类型单一。总之就是,还是不够灵活。虽然如此,工厂模式依旧十分优秀,并且适用于绝大多数情况。不过我们为了讲解后面的 依赖注入 ,这里就先夸大一下工厂模式的缺陷咯。

我们知道,超人依赖的模组,我们要求有统一的接口,这样才能和超人身上的注入接口对接,最终起到提升超能力的效果。事实上,我之前说谎了,不仅仅只有一堆小怪兽,还有更多的大怪兽。嘿嘿。额,这时候似乎工厂的生产能力显得有些不足 —— 由于工厂模式下,所有的模组都已经在工厂类中安排好了,如果有新的、高级的模组加入,我们必须修改工厂类(好比增加新的生产线):

class SuperModuleFactory{    
public function makeModule($moduleName, $options)
    {        
    switch ($moduleName) {            
    case &#39;Fight&#39;:     
    return new Fight($options[0], $options[1]);            
    case &#39;Force&#39;:     
    return new Force($options[0]);            
    case &#39;Shot&#39;:     
    return new Shot($options[0], $options[1], $options[2]);            
    // case &#39;more&#39;: .......
            // case &#39;and more&#39;: .......
            // case &#39;and more&#39;: .......
            // case &#39;oh no! its too many!&#39;: .......
        }
    }
}

看到没。。。噩梦般的感受!

其实灵感就差一步!你可能会想到更为灵活的办法!对,下一步就是我们今天的主要配角 —— DI (依赖注入)

由于对超能力模组的需求不断增大,我们需要集合整个世界的高智商人才,一起解决问题,不应该仅仅只有几个工厂垄断负责。不过高智商人才们都非常自负,认为自己的想法是对的,创造出的超能力模组没有统一的接口,自然而然无法被正常使用。这时我们需要提出一种契约,这样无论是谁创造出的模组,都符合这样的接口,自然就可被正常使用。

interface SuperModuleInterface{    /**
     * 超能力激活方法
     *
     * 任何一个超能力都得有该方法,并拥有一个参数
     *@param array $target 针对目标,可以是一个或多个,自己或他人
     */
    public function activate(array $target);
}

上文中,我们定下了一个接口 (超能力模组的规范、契约),所有被创造的模组必须遵守该规范,才能被生产。
其实,这就是 php 中 接口( interface ) 的用处和意义!很多人觉得,为什么 php 需要接口这种东西?难道不是 java 、 C# 之类的语言才有的吗?这么说,只要是一个正常的面向对象编程语言(虽然 php 可以面向过程),都应该具备这一特性。因为一个 对象(object) 本身是由他的模板或者原型 —— 类 (class) ,经过实例化后产生的一个具体事物,而有时候,实现统一种方法且不同功能(或特性)的时候,会存在很多的类(class),这时候就需要有一个契约,让大家编写出可以被随时替换却不会产生影响的接口。这种由编程语言本身提出的硬性规范,会增加更多优秀的特性。

这时候,那些提出更好的超能力模组的高智商人才,遵循这个接口,创建了下述(模组)类:

/**
 * X-超能量
 */class XPower implements SuperModuleInterface{    
 public function activate(array $target)
    {        
    // 这只是个例子。。具体自行脑补
    }
}/**
 * 终极* (就这么俗)
 */class UltraBomb implements SuperModuleInterface{    
 public function activate(array $target)
    {        
    // 这只是个例子。。具体自行脑补
    }
}

同时,为了防止有些 “砖家” 自作聪明,或者一些叛徒恶意捣蛋,不遵守契约胡乱制造模组,影响超人,我们对超人初始化的方法进行改造:

class Superman{    
protected $module;    
public function __construct(SuperModuleInterface $module)
    {        
    $this->module = $module
    }
}

改造完毕!现在,当我们初始化 “超人” 类的时候,提供的模组实例必须是一个 SuperModuleInterface 接口的实现。否则就会提示错误。

正是由于超人的创造变得容易,一个超人也就不需要太多的超能力,我们可以创造多个超人,并分别注入需要的超能力模组即可。这样的话,虽然一个超人只有一个超能力,但超人更容易变多,我们也不怕怪兽啦!

现在有人疑惑了,你要讲的 依赖注入 呢?
其实,上面讲的内容,正是依赖注入。

什么叫做 依赖注入?
本文从开头到现在提到的一系列依赖,只要不是由内部生产(比如初始化、构造函数 __construct 中通过工厂方法、自行手动 new 的),而是由外部以参数或其他形式注入的,都属于 依赖注入(DI) 。是不是豁然开朗?事实上,就是这么简单。下面就是一个典型的依赖注入:

// 超能力模组
$superModule = new XPower;
// 初始化一个超人,并注入一个超能力模组依赖
$superMan = new Superman($superModule);

关于依赖注入这个本文的主要配角,也就这么多需要讲的。理解了依赖注入,我们就可以继续深入问题。慢慢走近今天的主角……

IoC 容器诞生的故事——科技时代(IoC容器)

刚刚列了一段代码:

$superModule = new XPower;
$superMan = new Superman($superModule);

读者应该看出来了,手动的创建了一个超能力模组、手动的创建超人并注入了刚刚创建超能力模组。呵呵,手动

现代社会,应该是高效率的生产,干净的车间,完美的自动化装配。

一群怪兽来了,如此低效率产出超人是不现实,我们需要自动化 —— 最多一条指令,千军万马来相见。我们需要一种高级的生产车间,我们只需要向生产车间提交一个脚本,工厂便能够通过指令自动化生产。这种更为高级的工厂,就是工厂模式的升华 —— IoC 容器。

class Container{    
protected $binds;    
protected $instances;    
public function bind($abstract, $concrete)
    {        
    if ($concrete instanceof Closure) {            
    $this->binds[$abstract] = $concrete;
        } else {            
        $this->instances[$abstract] = $concrete;
        }
    }    public function make($abstract, $parameters = [])
    {        
    if (isset($this->instances[$abstract])) {            
    return $this->instances[$abstract];
        }

        array_unshift($parameters, $this);        
        return call_user_func_array($this->binds[$abstract], $parameters);
    }
}

这时候,一个十分粗糙的容器就诞生了。现在的确很简陋,但不妨碍我们进一步提升他。先着眼现在,看看这个容器如何使用吧!

// 创建一个容器(后面称作超级工厂)
$container = new Container;
// 向该 超级工厂 添加 超人 的生产脚本
$container->bind(&#39;superman&#39;, function($container, $moduleName) {    
return new Superman($container->make($moduleName));
});
// 向该 超级工厂 添加 超能力模组 的生产脚本
$container->bind(&#39;xpower&#39;, function($container) {    
return new XPower;
});
// 同上$container->bind(&#39;ultrabomb&#39;, function($container) {    
return new UltraBomb;
});
// ******************  华丽丽的分割线  **********************
// 开始启动生产
$superman_1 = $container->make(&#39;superman&#39;, &#39;xpower&#39;);
$superman_2 = $container->make(&#39;superman&#39;, &#39;ultrabomb&#39;);
$superman_3 = $container->make(&#39;superman&#39;, &#39;xpower&#39;);
// ...随意添加

看到没?通过最初的 绑定(bind) 操作,我们向 超级工厂 注册了一些生产脚本,这些生产脚本在生产指令下达之时便会执行。发现没有?我们彻底的解除了 超人 与 超能力模组 的依赖关系,更重要的是,容器类也丝毫没有和他们产生任何依赖!我们通过注册、绑定的方式向容器中添加一段可以被执行的回调(可以是匿名函数、非匿名函数、类的方法)作为生产一个类的实例的 脚本 ,只有在真正的 生产(make) 操作被调用执行时,才会触发。

这样一种方式,使得我们更容易在创建一个实例的同时解决其依赖关系,并且更加灵活。当有新的需求,只需另外绑定一个“生产脚本”即可。

实际上,真正的 IoC 容器更为高级。我们现在的例子中,还是需要手动提供超人所需要的模组参数,但真正的 IoC 容器会根据类的依赖需求,自动在注册、绑定的一堆实例中搜寻符合的依赖需求,并自动注入到构

现在,到目前为止,我们已经不再惧怕怪兽们了。高智商人才集思广益,井井有条,根据接口契约创造规范的超能力模组。超人开始批量产出。最终,人人都是超人,你也可以是哦 :stuck_out_tongue_closed_eyes:!

laravel初始化一个服务容器的大概过程

对于laravel初始化服务容器的过程,还是以代码加注释的方式来大致的解释一下,初始化过程都做了什么工作

/public/index.php文件里面有一行初始化服务器容器的代码,调度的相关文件就是:/bootstrap/app.php

代码清单/bootstrap/app.php

<?php
//真正的初始化服务容器代码,下面有此行的继续追踪
$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.&#39;/../&#39;)
);
//单例一个App\Http\Kernel对象,可以使用App::make(&#39;Illuminate\Contracts\Http\Kernel&#39;)调用
$app->singleton(    
&#39;Illuminate\Contracts\Http\Kernel&#39;,    
&#39;App\Http\Kernel&#39;);
//单例一个App\Console\Kernel对象,可以使用App::make(&#39;Illuminate\Contracts\Console\Kernel&#39;)调用
$app->singleton(    
&#39;Illuminate\Contracts\Console\Kernel&#39;,    
&#39;App\Console\Kernel&#39;);
//打字好累,同上,不解释
$app->singleton(    
&#39;Illuminate\Contracts\Debug\ExceptionHandler&#39;,    
&#39;App\Exceptions\Handler&#39;);
//返回一个初始化完成的服务容器
return $app;

代码清单Illuminate\Foundation\Application

//代码太多,只能解释几个主要的方法(真实情况是,我了解也不多,也就看了这几个方法*^_^*)
public function __construct($basePath = null)
    {        
    //初始化最简单的容器
        $this->registerBaseBindings();        
        //在容器中注册最基本的服务提供者(即ServiceProvider)
        $this->registerBaseServiceProviders();        
        //在容器中注册一些核心类的别名(这个说法貌似有点不妥,可以参见以下的代码注释自己再理解一下)
        $this->registerCoreContainerAliases();        
        //在容器中注册一些常用的文档绝对路径
        if ($basePath) $this->setBasePath($basePath);
    }    protected function registerBaseBindings()
    {        //初始化一个空的容器
        static::setInstance($this);        
        //在容器中,实例化一个key为app的实例,相对的值就是当前容器,你可以使用App::make(&#39;app&#39;)来取得一个容器对象
        $this->instance(&#39;app&#39;, $this);        
        //同上
        $this->instance(&#39;Illuminate\Container\Container&#39;, $this);
    }    protected function registerBaseServiceProviders()
    {        
    //EventServiceProvider这个服务提供者,其实是向容器注册了一个key为events的对象,可以在你的IDE里面追踪一下代码
        $this->register(new EventServiceProvider($this));        
        //注册4个key分别为router、url、redirect、Illuminate\Contracts\Routing\ResponseFactory的对象
        $this->register(new RoutingServiceProvider($this));
    }    /*这个方法的作用,就以一个例子来解释吧(语文不太好~\(≧▽≦)/~)
        在调用此方法之前,我们想取得一个容器实例的做法是 App::make(&#39;app&#39;);
        现在我们可以使用App::make(&#39;Illuminate\Foundation\Application&#39;)
        App::make(&#39;Illuminate\Contracts\Container\Container&#39;)
        App::make(&#39;Illuminate\Contracts\Foundation\Application&#39;)
        三种方法来取得一个容器实例,即Illuminate\Foundation\Application、Illuminate\Contracts\Container\Container、Illuminate\Contracts\Foundation\Application三者都是app的别名;
    */
    public function registerCoreContainerAliases()
    {        
    $aliases = array(            
    &#39;app&#39;                  
    => [&#39;Illuminate\Foundation\Application&#39;, &#39;Illuminate\Contracts\Container\Container&#39;, &#39;Illuminate\Contracts\Foundation\Application&#39;],            
    &#39;artisan&#39;              
    => [&#39;Illuminate\Console\Application&#39;, &#39;Illuminate\Contracts\Console\Application&#39;],            
    &#39;auth&#39;                 
    => &#39;Illuminate\Auth\AuthManager&#39;,            
    &#39;auth.driver&#39;          
    => [&#39;Illuminate\Auth\Guard&#39;, &#39;Illuminate\Contracts\Auth\Guard&#39;],            
    &#39;auth.password.tokens&#39; => &#39;Illuminate\Auth\Passwords\TokenRepositoryInterface&#39;,            
    &#39;blade.compiler&#39;       
    => &#39;Illuminate\View\Compilers\BladeCompiler&#39;,            
    &#39;cache&#39;                
    => [&#39;Illuminate\Cache\CacheManager&#39;, &#39;Illuminate\Contracts\Cache\Factory&#39;],            
    &#39;cache.store&#39;          
    => [&#39;Illuminate\Cache\Repository&#39;, &#39;Illuminate\Contracts\Cache\Repository&#39;],            
    &#39;config&#39;               
    => [&#39;Illuminate\Config\Repository&#39;, &#39;Illuminate\Contracts\Config\Repository&#39;],            
    &#39;cookie&#39;               
    => [&#39;Illuminate\Cookie\CookieJar&#39;, &#39;Illuminate\Contracts\Cookie\Factory&#39;, &#39;Illuminate\Contracts\Cookie\QueueingFactory&#39;],            
    &#39;encrypter&#39;            
    => [&#39;Illuminate\Encryption\Encrypter&#39;, &#39;Illuminate\Contracts\Encryption\Encrypter&#39;],            
    &#39;db&#39;                   
    => &#39;Illuminate\Database\DatabaseManager&#39;,            
    &#39;events&#39;               
    => [&#39;Illuminate\Events\Dispatcher&#39;, &#39;Illuminate\Contracts\Events\Dispatcher&#39;],            
    &#39;files&#39;                
    => &#39;Illuminate\Filesystem\Filesystem&#39;,            
    &#39;filesystem&#39;           
    => &#39;Illuminate\Contracts\Filesystem\Factory&#39;,           
    &#39;filesystem.disk&#39;      
    => &#39;Illuminate\Contracts\Filesystem\Filesystem&#39;,            
    &#39;filesystem.cloud&#39;     
    => &#39;Illuminate\Contracts\Filesystem\Cloud&#39;,            
    &#39;hash&#39;                 
    => &#39;Illuminate\Contracts\Hashing\Hasher&#39;,            
    &#39;translator&#39;           
    => [&#39;Illuminate\Translation\Translator&#39;, &#39;Symfony\Component\Translation\TranslatorInterface&#39;],            
    &#39;log&#39;                  
    => [&#39;Illuminate\Log\Writer&#39;, &#39;Illuminate\Contracts\Logging\Log&#39;, &#39;Psr\Log\LoggerInterface&#39;],            
    &#39;mailer&#39;               
    => [&#39;Illuminate\Mail\Mailer&#39;, &#39;Illuminate\Contracts\Mail\Mailer&#39;, &#39;Illuminate\Contracts\Mail\MailQueue&#39;],            
    &#39;paginator&#39;            
    => &#39;Illuminate\Pagination\Factory&#39;,            
    &#39;auth.password&#39;        
    => [&#39;Illuminate\Auth\Passwords\PasswordBroker&#39;, &#39;Illuminate\Contracts\Auth\PasswordBroker&#39;],            
    &#39;queue&#39;                
    => [&#39;Illuminate\Queue\QueueManager&#39;, &#39;Illuminate\Contracts\Queue\Factory&#39;, &#39;Illuminate\Contracts\Queue\Monitor&#39;],            
    &#39;queue.connection&#39;     
    => &#39;Illuminate\Contracts\Queue\Queue&#39;,            
    &#39;redirect&#39;             
    => &#39;Illuminate\Routing\Redirector&#39;,            
    &#39;redis&#39;                
    => [&#39;Illuminate\Redis\Database&#39;, &#39;Illuminate\Contracts\Redis\Database&#39;],            
    &#39;request&#39;              
    => &#39;Illuminate\Http\Request&#39;,            
    &#39;router&#39;               
    => [&#39;Illuminate\Routing\Router&#39;, &#39;Illuminate\Contracts\Routing\Registrar&#39;],            
    &#39;session&#39;              
    => &#39;Illuminate\Session\SessionManager&#39;,            
    &#39;session.store&#39;        
    => [&#39;Illuminate\Session\Store&#39;, &#39;Symfony\Component\HttpFoundation\Session\SessionInterface&#39;],            
    &#39;url&#39;                  
    => [&#39;Illuminate\Routing\UrlGenerator&#39;, &#39;Illuminate\Contracts\Routing\UrlGenerator&#39;],            
    &#39;validator&#39;            
    => [&#39;Illuminate\Validation\Factory&#39;, &#39;Illuminate\Contracts\Validation\Factory&#39;],            
    &#39;view&#39;                 
    => [&#39;Illuminate\View\Factory&#39;, &#39;Illuminate\Contracts\View\Factory&#39;],
        );        
        foreach ($aliases as $key => $aliases)
        {            
        foreach ((array) $aliases as $alias)
            {                
            $this->alias($key, $alias);
            }
        }
    }

由此得到的一个容器实例

Application {#2 ▼
  #basePath: "/Applications/XAMPP/xamppfiles/htdocs/laravel"
  #hasBeenBootstrapped: false
  #booted: false
  #bootingCallbacks: []
  #bootedCallbacks: []
  #terminatingCallbacks: []
  #serviceProviders: array:2 [▶]
  #loadedProviders: array:2 [▶]
  #deferredServices: []
  #storagePath: null
  #environmentFile: ".env"
  #resolved: array:1 [▶]
  #bindings: array:8 [▼
    "events" => array:2 [▶]    
    "router" => array:2 [▶]    
    "url" => array:2 [▶]    
    "redirect" => array:2 [▶]    
    "Illuminate\Contracts\Routing\ResponseFactory" => array:2 [▶]    
    "Illuminate\Contracts\Http\Kernel" => array:2 [▶]    
    "Illuminate\Contracts\Console\Kernel" => array:2 [▶]    
    "Illuminate\Contracts\Debug\ExceptionHandler" => array:2 [▶]
  ]  #instances: array:10 [▼
    "app" => Application {#2}
    "Illuminate\Container\Container" => Application {#2}
    "events" => Dispatcher {#5 ▶}
    "path" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/app"
    "path.base" => "/Applications/XAMPP/xamppfiles/htdocs/laravel"
    "path.config" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/config"
    "path.database" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/database"
    "path.lang" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/resources/lang"
    "path.public" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/public"
    "path.storage" => "/Applications/XAMPP/xamppfiles/htdocs/laravel/storage"
  ]  #aliases: array:59 [▼
    "Illuminate\Foundation\Application" => "app"
    "Illuminate\Contracts\Container\Container" => "app"
    "Illuminate\Contracts\Foundation\Application" => "app"
    "Illuminate\Console\Application" => "artisan"
    "Illuminate\Contracts\Console\Application" => "artisan"
    "Illuminate\Auth\AuthManager" => "auth"
    "Illuminate\Auth\Guard" => "auth.driver"
    "Illuminate\Contracts\Auth\Guard" => "auth.driver"
    "Illuminate\Auth\Passwords\TokenRepositoryInterface" => "auth.password.tokens"
    "Illuminate\View\Compilers\BladeCompiler" => "blade.compiler"
    "Illuminate\Cache\CacheManager" => "cache"
    "Illuminate\Contracts\Cache\Factory" => "cache"
    "Illuminate\Cache\Repository" => "cache.store"
    "Illuminate\Contracts\Cache\Repository" => "cache.store"
    "Illuminate\Config\Repository" => "config"
    "Illuminate\Contracts\Config\Repository" => "config"
    "Illuminate\Cookie\CookieJar" => "cookie"
    "Illuminate\Contracts\Cookie\Factory" => "cookie"
    "Illuminate\Contracts\Cookie\QueueingFactory" => "cookie"
    "Illuminate\Encryption\Encrypter" => "encrypter"
    "Illuminate\Contracts\Encryption\Encrypter" => "encrypter"
    "Illuminate\Database\DatabaseManager" => "db"
    "Illuminate\Events\Dispatcher" => "events"
    "Illuminate\Contracts\Events\Dispatcher" => "events"
    "Illuminate\Filesystem\Filesystem" => "files"
    "Illuminate\Contracts\Filesystem\Factory" => "filesystem"
    "Illuminate\Contracts\Filesystem\Filesystem" => "filesystem.disk"
    "Illuminate\Contracts\Filesystem\Cloud" => "filesystem.cloud"
    "Illuminate\Contracts\Hashing\Hasher" => "hash"
    "Illuminate\Translation\Translator" => "translator"
    "Symfony\Component\Translation\TranslatorInterface" => "translator"
    "Illuminate\Log\Writer" => "log"
    "Illuminate\Contracts\Logging\Log" => "log"
    "Psr\Log\LoggerInterface" => "log"
    "Illuminate\Mail\Mailer" => "mailer"
    "Illuminate\Contracts\Mail\Mailer" => "mailer"
    "Illuminate\Contracts\Mail\MailQueue" => "mailer"
    "Illuminate\Pagination\Factory" => "paginator"
    "Illuminate\Auth\Passwords\PasswordBroker" => "auth.password"
    "Illuminate\Contracts\Auth\PasswordBroker" => "auth.password"
    "Illuminate\Queue\QueueManager" => "queue"
    "Illuminate\Contracts\Queue\Factory" => "queue"
    "Illuminate\Contracts\Queue\Monitor" => "queue"
    "Illuminate\Contracts\Queue\Queue" => "queue.connection"
    "Illuminate\Routing\Redirector" => "redirect"
    "Illuminate\Redis\Database" => "redis"
    "Illuminate\Contracts\Redis\Database" => "redis"
    "Illuminate\Http\Request" => "request"
    "Illuminate\Routing\Router" => "router"
    "Illuminate\Contracts\Routing\Registrar" => "router"
    "Illuminate\Session\SessionManager" => "session"
    "Illuminate\Session\Store" => "session.store"
    "Symfony\Component\HttpFoundation\Session\SessionInterface" => "session.store"
    "Illuminate\Routing\UrlGenerator" => "url"
    "Illuminate\Contracts\Routing\UrlGenerator" => "url"
    "Illuminate\Validation\Factory" => "validator"
    "Illuminate\Contracts\Validation\Factory" => "validator"
    "Illuminate\View\Factory" => "view"
    "Illuminate\Contracts\View\Factory" => "view"
  ]  #extenders: []
  #tags: []
  #buildStack: []
  +contextual: []  #reboundCallbacks: []
  #globalResolvingCallbacks: []
  #globalAfterResolvingCallbacks: []
  #resolvingCallbacks: []
  #afterResolvingCallbacks: []}

怎么打印一个实例??
到这一步为止,你可以这样做dd(app())

dd(app())什么意思??
这里包含两个方法dd()和app(),具体定义请看自动加载的第四种方法

那说好的App::make(‘app’)方法咋不能用呢?
这是因为这个方法需要用到Contracts,而到此为止,还未定义App作为Illuminate\Support\Facades\App的别名,因而不能用;需要等到统一入口文件里面的运行Kernel类的handle方法才能用,所以在Controller里面是可以用的,现在不能用

到此为止,一个容器实例就诞生了,事情就是这么个事情,情况就是这个个情况,再具体的那就需要你自己去看代码了,我知道的就这些

启动Kernel代码

Kernel实例调用handle方法,意味着laravel的核心和公用代码已经准备完毕,此项目正式开始运行

代码清单/app/Http/Kernel.php

<?php 
namespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel {    
//这是在调用路由之前需要启动的中间件,一般都是核心文件,不要修改
    protected $middleware = [        
    &#39;Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode&#39;,        
    &#39;Illuminate\Cookie\Middleware\EncryptCookies&#39;,        
    &#39;Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse&#39;,        
    &#39;Illuminate\Session\Middleware\StartSession&#39;,        
    &#39;Illuminate\View\Middleware\ShareErrorsFromSession&#39;,        
    &#39;App\Http\Middleware\VerifyCsrfToken&#39;,
    ];    
    //这是我们在router.php文件里面或者Controller文件里面,可以使用的Middleware元素,可以自定义加入很多
    protected $routeMiddleware = [        
    &#39;auth&#39; => &#39;App\Http\Middleware\Authenticate&#39;,        
    &#39;auth.basic&#39; => &#39;Illuminate\Auth\Middleware\AuthenticateWithBasicAuth&#39;,        
    &#39;guest&#39; => &#39;App\Http\Middleware\RedirectIfAuthenticated&#39;,        
    &#39;test&#39; => &#39;App\Http\Middleware\testMiddleWare&#39;,
    ];

}

大家看到了,其实这个文件里面没有handle方法,只有一些属性定义,所以真正的handle方法,实在父类里面实现的

代码清单…/Illuminate/Foundation/Http/Kernel.php

//好多代码,见几个我看过的扯扯,其他的期待你们补上
//这个很重要,是项目的一些启动引导项,Kernel的重要步骤中,首先就是启动这些文件的bootstrap方法protected 
$bootstrappers = [        
                //检测环境变量文件是否正常
        &#39;Illuminate\Foundation\Bootstrap\DetectEnvironment&#39;,        
        //取得配置文件,即把/config/下的所有配置文件读取到容器(app()->make(&#39;config&#39;)可以查看所有配置信息)
        &#39;Illuminate\Foundation\Bootstrap\LoadConfiguration&#39;,        
        //绑定一个名字为log的实例到容器,怎么访问??(app()->make(&#39;log&#39;))
        &#39;Illuminate\Foundation\Bootstrap\ConfigureLogging&#39;,        
        //设置异常抓取信息,这个还没仔细看,但大概就是这个意思
        &#39;Illuminate\Foundation\Bootstrap\HandleExceptions&#39;,        
        //把/config/app.php里面的aliases项利用PHP库函数class_alias创建别名,从此,我们可以使用App::make(&#39;app&#39;)方式取得实例
        &#39;Illuminate\Foundation\Bootstrap\RegisterFacades&#39;,        
        //把/config/app.php里面的providers项,注册到容器
        &#39;Illuminate\Foundation\Bootstrap\RegisterProviders&#39;,        
        //运行容器中注册的所有的ServiceProvider中得boot方法
        &#39;Illuminate\Foundation\Bootstrap\BootProviders&#39;,
    ];  //真正的handle方法
  public function handle($request)
    {        try
        {            
        //主要是这行,调度了需要运行的方法
            return $this->sendRequestThroughRouter($request);
        }        
        catch (Exception $e)
        {            
        $this->reportException($e);            
        return $this->renderException($request, $e);
        }
    }    
    protected function sendRequestThroughRouter($request)
    {        
    $this->app->instance(&#39;request&#39;, $request);
        Facade::clearResolvedInstance(&#39;request&#39;);        
        //运行上述$bootstrappers里面包含的文件的bootstrap方法,运行的作用,上面已经注释
        $this->bootstrap();        
        //这是在对URL进行调度之前,也就是运行Route之前,进行的一些准备工作
        return (new Pipeline($this->app))    
        //不解释
                    ->send($request)        
                    //继续不解释
                    //需要运行$this->middleware里包含的中间件
                    ->through($this->middleware)                    
                    //运行完上述中间件之后,调度dispatchToRouter方法,进行Route的操作
                    ->then($this->dispatchToRouter());
    }    //前奏执行完毕之后,进行Route操作
    protected function dispatchToRouter()
    {        
    return function($request)
        {            
        $this->app->instance(&#39;request&#39;, $request);            
        //跳转到Router类的dispatch方法
            return $this->router->dispatch($request);
        };
    }

下面就需要根据URL和/app/Http/routes.php文件,进行Route操作

文件清单…/Illuminate/Routing/Router.php

//代码好多,挑几个解释

    public function dispatch(Request $request)
    {        
    $this->currentRequest = $request;        
    //在4.2版本里面,Route有一个筛选属性;5.0之后的版本,被Middleware代替
        $response = $this->callFilter(&#39;before&#39;, $request);        
        if (is_null($response))
        {    
            //继续调度
            $response = $this->dispatchToRoute($request);
        }        $response = $this->prepareResponse($request, $response);        
        //在4.2版本里面,Route有一个筛选属性;5.0之后的版本,被Middleware代替
        $this->callFilter(&#39;after&#39;, $request, $response);        
        return $response;
    }    
    public function dispatchToRoute(Request $request)
    {        
    $route = $this->findRoute($request);        
    $request->setRouteResolver(function() use ($route)
        {            
        return $route;
        });        
        $this->events->fire(&#39;router.matched&#39;, [$route, $request]);        
        $response = $this->callRouteBefore($route, $request);        
        if (is_null($response))
        {            // 只看这一行,还是调度文件
            $response = $this->runRouteWithinStack(                
            $route, $request
            );
        }        
        $response = $this->prepareResponse($request, $response);        
        $this->callRouteAfter($route, $request, $response);        
        return $response;
    }    //干货来了
    protected function runRouteWithinStack(Route $route, Request $request)
    {        
    // 取得routes.php里面的Middleware节点
        $middleware = $this->gatherRouteMiddlewares($route);        
        //这个有点眼熟
        return (new Pipeline($this->container))
                        ->send($request)                        
                        //执行上述的中间件
                        ->through($middleware)
                        ->then(function($request) use ($route)
                        {    
                            //不容易啊,终于到Controller类了
                            return $this->prepareResponse(                                
                            $request,                                
                            //run控制器
                                $route->run($request)
                            );
                        });
    }    
    public function run(Request $request)
    {        
    $this->container = $this->container ?: new Container;        
    try
        {            
        if ( ! is_string($this->action[&#39;uses&#39;]))                
        return $this->runCallable($request);            
        if ($this->customDispatcherIsBound())            
        //实际上是运行了这行
                return $this->runWithCustomDispatcher($request);            
                //其实我是直接想运行这行
            return $this->runController($request);
        }        
        catch (HttpResponseException $e)
        {            
        return $e->getResponse();
        }
    }    
    //继续调度,最终调度到.../Illuminate/Routing/ControllerDispatcher.php文件的dispatch方法
    protected function runWithCustomDispatcher(Request $request)
    {        
    list($class, $method) = explode(&#39;@&#39;, $this->action[&#39;uses&#39;]);        
    $dispatcher = $this->container->make(&#39;illuminate.route.dispatcher&#39;);        
    return $dispatcher->dispatch($this, $request, $class, $method);
    }

文件清单…/Illuminate/Routing/ControllerDispatcher.php

    public function dispatch(Route $route, Request $request, $controller, $method)
    {        
    $instance = $this->makeController($controller);        
    $this->assignAfter($instance, $route, $request, $method);        
    $response = $this->before($instance, $route, $request, $method);        
    if (is_null($response))
        {            
        //还要调度
            $response = $this->callWithinStack(                
            $instance, $route, $request, $method
            );
        }        
        return $response;
    }    protected function callWithinStack($instance, $route, $request, $method)
    {        
    //又是Middleware......有没有忘记,官方文档里面Middleware可以加在控制器的构造函数中!!没错,这个Middleware就是在控制器里面申明的
        $middleware = $this->getMiddleware($instance, $method);        
        //又是这个,眼熟吧
        return (new Pipeline($this->container))
                    ->send($request)                    
                    //再次运行Middleware
                    ->through($middleware)
                    ->then(function($request) use ($instance, $route, $method)
                    {    
                        运行控制器,返回结果                        
                        return $this->call($instance, $route, $method);
                    });
    }

这就是从入口文件到控制器中间,进行的一系列操作,心塞塞的,终于到我们干活的地方了

相关文章推荐:
Laravel框架内置的Broadcast功能如何实现与客户端实时通信

相关课程推荐:

2017年最新的五个Laravel视频教程推荐

Das obige ist der detaillierte Inhalt vonAnalyse des Startvorgangs des Laravel-Frameworks. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn