您好,欢迎访问一九零五行业门户网

Laravel Facade 的详细解读

下面由laravel教程栏目给大家介绍laravel facade 的详细解读,希望对需要的朋友有所帮助!
大家好,今天带来的内容是 laravel 的 facade 机制实现原理。
facade的简单使用数据库的使用:
$users = db::connection('foo')->select(...);
ioc容器众所周知,ioc容器是 laravel 框架的最最重要的部分。它提供了两个功能,ioc和容器。
ioc(inversion of control),也叫控制反转。说白了,就是控制对象的生成,使开发者不用关心对象的如何生成,只需要关心它的使用即可。而通过ioc机制生成的对象实例需要一个存放的位置,以便之后继续使用,便是它的容器功能。这次不准备讲解ioc容器的具体实现,之后会有文章详细解读它。关于ioc容器,读者只需要记住两点即可:
根据配置生成对象实例;保存对象实例,方便随时取用;简化后 facade 类<?phpnamespace facades;abstract class facade{ protected static $app; /** * set the application instance. * * @param \illuminate\contracts\foundation\application $app * @return void */ public static function setfacadeapplication($app) { static::$app = $app; } /** * get the registered name of the component. * * @return string * * @throws \runtimeexception */ protected static function getfacadeaccessor() { throw new runtimeexception('facade does not implement getfacadeaccessor method.'); } /** * get the root object behind the facade. * * @return mixed */ public static function getfacaderoot() { return static::resolvefacadeinstance(static::getfacadeaccessor()); } /** * resolve the facade root instance from the container. * * @param string|object $name * @return mixed */ protected static function resolvefacadeinstance($name) { return static::$app->instances[$name]; } public static function __callstatic($method, $args) { $instance = static::getfacaderoot(); if (! $instance) { throw new runtimeexception('a facade root has not been set.'); } switch (count($args)) { case 0: return $instance->$method(); case 1: return $instance->$method($args[0]); case 2: return $instance->$method($args[0], $args[1]); case 3: return $instance->$method($args[0], $args[1], $args[2]); case 4: return $instance->$method($args[0], $args[1], $args[2], $args[3]); default: return call_user_func_array([$instance, $method], $args); } }}
代码说明:
$app中存放的就是一个ioc容器实例,它是在框架初始化时,通过 setfacadeapplication() 这个静态方法设置的它实现了 __callstatic 魔术方法getfacadeaccessor() 方法需要子类去继承,返回一个string的标识,通过这个标识,ioc容器便能返回它所绑定类(框架初始化或其它时刻绑定)的对象通过 $instance 调用具体的方法创建自己的facade:test1 的具体逻辑:
<?phpclass test1{ public function hello() { print("hello world"); }}
test1 类的facade:
<?phpnamespace facades;/** * class test1 * @package facades * * @method static setoverrecommendinfo [设置播放完毕时的回调函数] * @method static sethandlerplayer [明确指定下一首时的执行类] */class test1facade extends facade{ protected static function getfacadeaccessor() { return 'test1'; } }
使用:
use facades\test1facade;test1facade::hello(); // 这是 facade 调用
解释:
facades\test1facade 调用静态方法 hello() 时,由于没有定义此方法,会调用 __callstatic;在 __callstatic 中,首先是获取对应的实例,即 return static::$app->instances[$name];。这其中的 $name,即为 facades\test1 里的 test1$app, 即为 ioc 容器,类的实例化过程,就交由它来处理。以上就是laravel facade 的详细解读的详细内容。
其它类似信息

推荐信息