容器解答

来源:互联网 发布:Java bint 编辑:程序博客网 时间:2024/05/17 06:21
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 'Fight':     return new Fight($options[0], $options[1]);            case 'Force':     return new Force($options[0]);            case 'Shot':     return new Shot($options[0], $options[1], $options[2]);        }    }}
这时候,超人 创建之初就可以使用这个工厂!
class Superman{    protected $power;    public function __construct()    {        // 初始化工厂        $factory = new SuperModuleFactory;        // 通过工厂提供的方法制造需要的模块        $this->power = $factory->makeModule('Fight', [9, 100]);        // $this->power = $factory->makeModule('Force', [45]);        // $this->power = $factory->makeModule('Shot', [99, 50, 2]);        /*        $this->power = array(            $factory->makeModule('Force', [45]),            $factory->makeModule('Shot', [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([    'Fight' => [9, 100],     'Shot' => [99, 50, 2]    ]);
现在修改的结果令人满意。现在,“超人” 的创建不再依赖任何一个 “超能力” 的类,我们如若修改了或者增加了新的超能力,只需要针对修改 SuperModuleFactory 即可。扩充超能力的同时不再需要重新编辑超人的类文件,使得我们变得很轻松。但是,这才刚刚开始。
IoC 容器诞生的故事——铁器时代(依赖注入)
由 “超人” 对 “超能力” 的依赖变成 “超人” 对 “超能力模组工厂” 的依赖后,对付小怪兽们变得更加得心应手。但这也正如你所看到的,依赖并未解除,只是由原来对多个外部的依赖变成了对一个 “工厂” 的依赖。假如工厂出了点麻烦,问题变得就很棘手。


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


我们知道,超人依赖的模组,我们要求有统一的接口,这样才能和超人身上的注入接口对接,最终起到提升超能力的效果。事实上,我之前说谎了,不仅仅只有一堆小怪兽,还有更多的大怪兽。嘿嘿。额,这时候似乎工厂的生产能力显得有些不足 —— 由于工厂模式下,所有的模组都已经在工厂类中安排好了,如果有新的、高级的模组加入,我们必须修改工厂类(好比增加新的生产线):
class SuperModuleFactory{    public function makeModule($moduleName, $options)    {        switch ($moduleName) {            case 'Fight':     return new Fight($options[0], $options[1]);            case 'Force':     return new Force($options[0]);            case 'Shot':     return new Shot($options[0], $options[1], $options[2]);            // case 'more': .......            // case 'and more': .......            // case 'and more': .......            // case 'oh no! its too many!': .......        }    }}
看到没。。。噩梦般的感受!


其实灵感就差一步!你可能会想到更为灵活的办法!对,下一步就是我们今天的主要配角 —— 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('superman', function($container, $moduleName) {    return new Superman($container->make($moduleName));});// 向该 超级工厂 添加 超能力模组 的生产脚本$container->bind('xpower', function($container) {    return new XPower;});// 同上$container->bind('ultrabomb', function($container) {    return new UltraBomb;});// ******************  华丽丽的分割线  **********************// 开始启动生产$superman_1 = $container->make('superman', 'xpower');$superman_2 = $container->make('superman', 'ultrabomb');$superman_3 = $container->make('superman', 'xpower');// ...随意添加
看到没?通过最初的 绑定(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__.'/../'));//单例一个App\Http\Kernel对象,可以使用App::make('Illuminate\Contracts\Http\Kernel')调用$app->singleton(    'Illuminate\Contracts\Http\Kernel',    'App\Http\Kernel');//单例一个App\Console\Kernel对象,可以使用App::make('Illuminate\Contracts\Console\Kernel')调用$app->singleton(    'Illuminate\Contracts\Console\Kernel',    'App\Console\Kernel');//打字好累,同上,不解释$app->singleton(    'Illuminate\Contracts\Debug\ExceptionHandler',    'App\Exceptions\Handler');//返回一个初始化完成的服务容器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('app')来取得一个容器对象        $this->instance('app', $this);        //同上        $this->instance('Illuminate\Container\Container', $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('app');        现在我们可以使用App::make('Illuminate\Foundation\Application')        App::make('Illuminate\Contracts\Container\Container')        App::make('Illuminate\Contracts\Foundation\Application')        三种方法来取得一个容器实例,即Illuminate\Foundation\Application、Illuminate\Contracts\Container\Container、Illuminate\Contracts\Foundation\Application三者都是app的别名;    */    public function registerCoreContainerAliases()    {        $aliases = array(            'app'                  => ['Illuminate\Foundation\Application', 'Illuminate\Contracts\Container\Container', 'Illuminate\Contracts\Foundation\Application'],            'artisan'              => ['Illuminate\Console\Application', 'Illuminate\Contracts\Console\Application'],            'auth'                 => 'Illuminate\Auth\AuthManager',            'auth.driver'          => ['Illuminate\Auth\Guard', 'Illuminate\Contracts\Auth\Guard'],            'auth.password.tokens' => 'Illuminate\Auth\Passwords\TokenRepositoryInterface',            'blade.compiler'       => 'Illuminate\View\Compilers\BladeCompiler',            'cache'                => ['Illuminate\Cache\CacheManager', 'Illuminate\Contracts\Cache\Factory'],            'cache.store'          => ['Illuminate\Cache\Repository', 'Illuminate\Contracts\Cache\Repository'],            'config'               => ['Illuminate\Config\Repository', 'Illuminate\Contracts\Config\Repository'],            'cookie'               => ['Illuminate\Cookie\CookieJar', 'Illuminate\Contracts\Cookie\Factory', 'Illuminate\Contracts\Cookie\QueueingFactory'],            'encrypter'            => ['Illuminate\Encryption\Encrypter', 'Illuminate\Contracts\Encryption\Encrypter'],            'db'                   => 'Illuminate\Database\DatabaseManager',            'events'               => ['Illuminate\Events\Dispatcher', 'Illuminate\Contracts\Events\Dispatcher'],            'files'                => 'Illuminate\Filesystem\Filesystem',            'filesystem'           => 'Illuminate\Contracts\Filesystem\Factory',            'filesystem.disk'      => 'Illuminate\Contracts\Filesystem\Filesystem',            'filesystem.cloud'     => 'Illuminate\Contracts\Filesystem\Cloud',            'hash'                 => 'Illuminate\Contracts\Hashing\Hasher',            'translator'           => ['Illuminate\Translation\Translator', 'Symfony\Component\Translation\TranslatorInterface'],            'log'                  => ['Illuminate\Log\Writer', 'Illuminate\Contracts\Logging\Log', 'Psr\Log\LoggerInterface'],            'mailer'               => ['Illuminate\Mail\Mailer', 'Illuminate\Contracts\Mail\Mailer', 'Illuminate\Contracts\Mail\MailQueue'],            'paginator'            => 'Illuminate\Pagination\Factory',            'auth.password'        => ['Illuminate\Auth\Passwords\PasswordBroker', 'Illuminate\Contracts\Auth\PasswordBroker'],            'queue'                => ['Illuminate\Queue\QueueManager', 'Illuminate\Contracts\Queue\Factory', 'Illuminate\Contracts\Queue\Monitor'],            'queue.connection'     => 'Illuminate\Contracts\Queue\Queue',            'redirect'             => 'Illuminate\Routing\Redirector',            'redis'                => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],            'request'              => 'Illuminate\Http\Request',            'router'               => ['Illuminate\Routing\Router', 'Illuminate\Contracts\Routing\Registrar'],            'session'              => 'Illuminate\Session\SessionManager',            'session.store'        => ['Illuminate\Session\Store', 'Symfony\Component\HttpFoundation\Session\SessionInterface'],            'url'                  => ['Illuminate\Routing\UrlGenerator', 'Illuminate\Contracts\Routing\UrlGenerator'],            'validator'            => ['Illuminate\Validation\Factory', 'Illuminate\Contracts\Validation\Factory'],            'view'                 => ['Illuminate\View\Factory', 'Illuminate\Contracts\View\Factory'],        );        foreach ($aliases as $key => $aliases)        {            foreach ((array) $aliases as $alias)            {                $this->alias($key, $alias);            }        }    }
由此得到的一个容器实例
<code class="php" data-origin="" 
<code class="php" data-origin="" 
<code class="php" data-origin="" 
<code class="php" data-origin="" 
Application {#2 ▼">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
&lt;?php namespace App\Http;"><?php namespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel {    //这是在调用路由之前需要启动的中间件,一般都是核心文件,不要修改    protected $middleware = [        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',        'Illuminate\Cookie\Middleware\EncryptCookies',        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',        'Illuminate\Session\Middleware\StartSession',        'Illuminate\View\Middleware\ShareErrorsFromSession',        'App\Http\Middleware\VerifyCsrfToken',    ];    //这是我们在router.php文件里面或者Controller文件里面,可以使用的Middleware元素,可以自定义加入很多    protected $routeMiddleware = [        'auth' => 'App\Http\Middleware\Authenticate',        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',        'test' => 'App\Http\Middleware\testMiddleWare',    ];}
大家看到了,其实这个文件里面没有handle方法,只有一些属性定义,所以真正的handle方法,实在父类里面实现的


代码清单…/Illuminate/Foundation/Http/Kernel.php
//好多代码,见几个我看过的扯扯,其他的期待你们补上">//好多代码,见几个我看过的扯扯,其他的期待你们补上//这个很重要,是项目的一些启动引导项,Kernel的重要步骤中,首先就是启动这些文件的bootstrap方法protected $bootstrappers = [        //检测环境变量文件是否正常        'Illuminate\Foundation\Bootstrap\DetectEnvironment',        //取得配置文件,即把/config/下的所有配置文件读取到容器(app()->make('config')可以查看所有配置信息)        'Illuminate\Foundation\Bootstrap\LoadConfiguration',        //绑定一个名字为log的实例到容器,怎么访问??(app()->make('log'))        'Illuminate\Foundation\Bootstrap\ConfigureLogging',        //设置异常抓取信息,这个还没仔细看,但大概就是这个意思        'Illuminate\Foundation\Bootstrap\HandleExceptions',        //把/config/app.php里面的aliases项利用PHP库函数class_alias创建别名,从此,我们可以使用App::make('app')方式取得实例        'Illuminate\Foundation\Bootstrap\RegisterFacades',        //把/config/app.php里面的providers项,注册到容器        'Illuminate\Foundation\Bootstrap\RegisterProviders',        //运行容器中注册的所有的ServiceProvider中得boot方法        'Illuminate\Foundation\Bootstrap\BootProviders',    ];  //真正的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('request', $request);        Facade::clearResolvedInstance('request');        //运行上述$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('request', $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('before', $request);        if (is_null($response))        {                //继续调度            $response = $this->dispatchToRoute($request);        }        $response = $this->prepareResponse($request, $response);        //在4.2版本里面,Route有一个筛选属性;5.0之后的版本,被Middleware代替        $this->callFilter('after', $request, $response);        return $response;    }    public function dispatchToRoute(Request $request)    {        $route = $this->findRoute($request);        $request->setRouteResolver(function() use ($route)        {            return $route;        });        $this->events->fire('router.matched', [$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['uses']))                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('@', $this->action['uses']);        $dispatcher = $this->container->make('illuminate.route.dispatcher');        return $dispatcher->dispatch($this, $request, $class, $method);    }
文件清单…/Illuminate/Routing/ControllerDispatcher.php
    public function dispatch(Route $route, Request $request, $controller, $method)">    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);                    });    }
这就是从入口文件到控制器中间,进行的一系列操作,心塞塞的,终于到我们干活的地方了


                                             
0 0
原创粉丝点击