Home > Article > PHP Framework > Detailed interpretation of Laravel Facade
The following is a detailed explanation of Laravel Facade from the Laravel tutorial column. Hope it helps those in need!
Hello everyone, today’s content is about the implementation principle of Laravel’s Facade mechanism.
Use of database:
$users = DB::connection('foo')->select(...);
As we all know, the IOC container is the most important part of the Laravel framework. It provides two functions, IOC and containers.
This time I am not going to explain the specific implementation of the IOC container. There will be articles explaining it in detail later. Regarding IOC containers, readers only need to remember two points:
<?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); } } }
Code description:
TEST1 The specific logic:
<?php class Test1{ public function hello() { print("hello world"); }}
Facade of the TEST1 class:
<?php namespace facades;/** * Class Test1 * @package facades * * @method static setOverRecommendInfo [设置播放完毕时的回调函数] * @method static setHandlerPlayer [明确指定下一首时的执行类] */class Test1Facade extends Facade{ protected static function getFacadeAccessor() { return 'test1'; } }
Usage:
use facades\Test1Facade;Test1Facade::hello(); // 这是 Facade 调用
Explanation:
return static::$app->instances[$name ];
. The $name
is the test1
$app in The above is the detailed content of Detailed interpretation of Laravel Facade. For more information, please follow other related articles on the PHP Chinese website!