
下面由Laravel教程栏目给大家介绍Laravel Facade 的详细解读,希望对需要的朋友有所帮助!

大家好,今天带来的内容是 Laravel 的 Facade 机制实现原理。
数据库的使用:
$users = DB::connection('foo')->select(...);众所周知,IOC容器是 Laravel 框架的最最重要的部分。它提供了两个功能,IOC和容器。
这次不准备讲解IOC容器的具体实现,之后会有文章详细解读它。关于IOC容器,读者只需要记住两点即可:
<?php
namespace 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);
}
}
}代码说明:
TEST1 的具体逻辑:
<?php
class Test1{
public function hello()
{
print("hello world");
}}TEST1 类的Facade:
<?php
namespace 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 调用
解释:
return static::$app->instances[$name];。这其中的 $name,即为 facades\Test1 里的 test1