這篇文章給大家分享的是有關Laravel中Facade怎么用的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
數據庫的使用:
$users = DB::connection('foo')->select(...);眾所周知,IOC容器是 Laravel 框架的最最重要的部分。它提供了兩個功能,IOC和容器。
IOC(Inversion of Control),也叫控制反轉。說白了,就是控制對象的生成,使開發者不用關心對象的如何生成,只需要關心它的使用即可。
而通過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);
}
}
}代碼說明:
$app中存放的就是一個IOC容器實例,它是在框架初始化時,通過 setFacadeApplication() 這個靜態方法設置的
它實現了 __callStatic 魔術方法
getFacadeAccessor() 方法需要子類去繼承,返回一個string的標識,通過這個標識,IOC容器便能返回它所綁定類(框架初始化或其它時刻綁定)的對象
通過 $instance 調用具體的方法
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 調用
解釋:
facades\Test1Facade 調用靜態方法 hello() 時,由于沒有定義此方法,會調用 __callStatic;
在 __callStatic 中,首先是獲取對應的實例,即 return static::$app->instances[$name];。這其中的 $name,即為 facades\Test1 里的 test1
$app, 即為 IOC 容器,類的實例化過程,就交由它來處理。
感謝各位的閱讀!關于“Laravel中Facade怎么用”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。