-
Notifications
You must be signed in to change notification settings - Fork 80
Description
Laravel 有不少门面类,如
Session、View初一看令人诈舌,这些类的功能类不只一个,那么 Laravel 是怎么让这些奇葩的门面通往不止一个后门的?
类声明
| namespace Illuminate\Support; | |
| use Closure; | |
| use InvalidArgumentException; | |
| abstract class Manager | |
| { |
这是一个抽象类。
属性
laravel/vendor/laravel/framework/src/Illuminate/Support/Manager.php
Lines 10 to 29 in ca57c28
| /** | |
| * The application instance. | |
| * | |
| * @var \Illuminate\Foundation\Application | |
| */ | |
| protected $app; | |
| /** | |
| * The registered custom driver creators. | |
| * | |
| * @var array | |
| */ | |
| protected $customCreators = []; | |
| /** | |
| * The array of created "drivers". | |
| * | |
| * @var array | |
| */ | |
| protected $drivers = []; |
$app 是容器,这个 $customCreators 是什么鬼没看懂我们可以不管它。后面这个 $drivers,是一个数组,放的什么东西呢?
driver 在英语中是驱动器的意思。
算了。。。再这么讲下去太拖了。我们拉到最后
魔术函数
laravel/vendor/laravel/framework/src/Illuminate/Support/Manager.php
Lines 144 to 147 in ca57c28
| public function __call($method, $parameters) | |
| { | |
| return $this->driver()->$method(...$parameters); | |
| } |
我们看到,当调用到当前实现类不存在方法时会调用 $this->driver() 下的同名方法。
laravel/vendor/laravel/framework/src/Illuminate/Support/Manager.php
Lines 57 to 75 in ca57c28
| public function driver($driver = null) | |
| { | |
| $driver = $driver ?: $this->getDefaultDriver(); | |
| if (is_null($driver)) { | |
| throw new InvalidArgumentException(sprintf( | |
| 'Unable to resolve NULL driver for [%s].', static::class | |
| )); | |
| } | |
| // If the given driver has not been created before, we will create the instances | |
| // here and cache it so we can return it next time very quickly. If there is | |
| // already a driver created by this name, we'll just return that instance. | |
| if (! isset($this->drivers[$driver])) { | |
| $this->drivers[$driver] = $this->createDriver($driver); | |
| } | |
| return $this->drivers[$driver]; | |
| } |
然后 getDefaultDriver,
| abstract public function getDefaultDriver(); |
这是抽象函数,我们到具体的例子中看吧。比如 session
laravel/vendor/laravel/framework/src/Illuminate/Session/SessionManager.php
Lines 200 to 203 in ca57c28
| public function getDefaultDriver() | |
| { | |
| return $this->app['config']['session.driver']; | |
| } |
所以,这些继承于 Illuminate\Support\Manager 的门后类,实现了向 driver 的穿透。
总结: Manager first, driver end.
经理先行,司机垫后