xiaohuilam / laravel

Laravel 深入详解 —— 源代码解析,新手进阶指南

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

15. Laravel 神奇的 Manager 类

xiaohuilam opened this issue · comments

Laravel 有不少门面类,如 SessionView 初一看令人诈舌,这些类的功能类不只一个,那么 Laravel 是怎么让这些奇葩的门面通往不止一个后门的?

类声明

namespace Illuminate\Support;
use Closure;
use InvalidArgumentException;
abstract class Manager
{

这是一个抽象类。

属性

/**
* 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 在英语中是驱动器的意思。

算了。。。再这么讲下去太拖了。我们拉到最后

魔术函数

public function __call($method, $parameters)
{
return $this->driver()->$method(...$parameters);
}

我们看到,当调用到当前实现类不存在方法时会调用 $this->driver() 下的同名方法。

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

public function getDefaultDriver()
{
return $this->app['config']['session.driver'];
}


所以,这些继承于 Illuminate\Support\Manager 的门后类,实现了向 driver 的穿透。

总结: Manager first, driver end. 经理先行,司机垫后