laravel的启动过程,也是laravel的核心,对这个过程有一个了解,有助于驾轻就熟的使用框架,但愿能对你们有点帮助。 统一入口 laravel框架使用了统一入口,入口文件:/public/index.php
<?php
//自动加载文件设置
require __DIR__.'/../bootstrap/autoload.php';
//初始化服务容器(能够查看一下关于‘服务容器’的相关文档)
$app = require_once __DIR__.'/../bootstrap/app.php';
//经过服务容器生成一个kernel类的实例(Illuminate\Contracts\Http\Kernel实际上只是一个接口,真正生成的实例是App\Http\Kernel类,至于怎么把接口和类关联起来,请查看Contracts相关文档)
$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
//运行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('LARAVEL_START', microtime(true));
//这就是传说中Composer的自动加载文件
require __DIR__.'/../vendor/autoload.php';
//Composer自动生成的各个核心类的集合,若是你须要修改一些vendor里面的文件来查看一些laravel运行细节,那么就请删除此文件
$compiledPath = __DIR__.'/../vendor/compiled.php';
if (file_exists($compiledPath))
{
require $compiledPath;
}
代码清单 laravel/vendor/autoload.php
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
//别被吓到了,他就是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 ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit03dc6c3c47809c398817ca33ec5f6a01', 'loadClassLoader'));
$includePaths = require __DIR__ . '/include_paths.php';
array_push($includePaths, get_include_path());
set_include_path(join(PATH_SEPARATOR, $includePaths));
//Psr0标准-设置命名空间对应的路径,以便于随后自动加载相关类文件(看看psr0和psr4的区别)
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
//Psr4标准-设置命名空间对应的路径,以便于随后自动加载相关类文件(看看psr0和psr4的区别)
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
//设置类文件路径与类名的对应关系,以便于随后自动加载相关类文件(可能你有一部分类,因为历史缘由,他们的命名空间不遵照PSR0和PSR4,你就可使用此方法自动加载)
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
//根据上述三种方法注册自动加载文档的方法,能够查看一下PHP的spl_autoload_register和__autoload方法
$loader->register(true);
//加载公用方法,好比app()方法取得一个application实例,就是这里加载的,能够查看一下autoload_files.php文件都加载了什么公用方法,有不少关于 array的操做方法哦
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
composerRequire03dc6c3c47809c398817ca33ec5f6a01($file);
}
return $loader;
}
}
function composerRequire03dc6c3c47809c398817ca33ec5f6a01($file)
{
require $file;
}
对于laravel自动加载过程的总结 laravel自动加载的过程就是这样实现的,总结为四种加载方式: PSR0加载方式—对应的文件就是autoload_namespaces.php PSR4加载方式—对应的文件就是autoload_psr4.php 其余加载类的方式—对应的文件就是autoload_classmap.php 加载公用方法—对应的文件就是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 '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); } } } 由此获得的一个容器实例 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 = [ '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) { $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); }); }