laravel Facade
Facade的调用原理和过程
创建一个类 CacheManager.php(默认所有组件都在同一目录下)
创建一个provider CacheServiceProvider
class CacheServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('cache',function($app){ return new CacheManager($app); }); } }
服务容器($this->app)在服务提供者(ServiceProvider)内绑定服务(CacheManager)
singleton将类绑定到容器中
在config/app.php中注册服务提供者
'providers' => [ /* * Laravel Framework Service Providers... */ 'Illuminate\Cache\CacheServiceProvider', ]
创建facades,调用容器方法
class Cache extends Facade { protected static function getFacadeAccessor() { return 'cache'; } }
基类Facade
所有门脸类都是继承自Facade类,再该基类中定义了一个__callStatic方法,以至于我们可以轻松的使用facade
public static function __callStatic($method, $args) { $instance = static::getFacadeRoot(); if (! $instance) { throw new RuntimeException('A facade root has not been set.'); } return $instance->$method(...$args); }
public static function getFacadeRoot() { return static::resolveFacadeInstance(static::getFacadeAccessor()); }
getFacadeRoot方法将根据getFacadeAccessor()的返回值,从容器中取出对应的实例对象。
protected static function resolveFacadeInstance($name) { if (is_object($name)) { return $name; } if (isset(static::$resolvedInstance[$name])) { return static::$resolvedInstance[$name]; } return static::$resolvedInstance[$name] = static::$app[$name]; }