PHP Laravel門面的實(shí)現(xiàn)原理詳解
環(huán)境
Laravel 5.4
原理
在Laravel中,門面為應(yīng)用服務(wù)容器中綁定的類提供了一個(gè)“靜態(tài)”接口,使得我們可以不用new這些類出來,就可以直接通過靜態(tài)接口調(diào)用這些類中的方法。
下面我們先看看一個(gè)門面類是怎么定義的:
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Player extends Facade
{
protected static function getFacadeAccessor() {
return 'player';
}
}
門面類都繼承自Illuminate\Support\Facades\Facade父類,這個(gè)父類中有一個(gè)魔術(shù)方法:
/**
* Handle dynamic, static calls to the object.
*
* @param string $method
* @param array $args
* @return mixed
*
* @throws \RuntimeException
*/
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);
}
當(dāng)我們靜態(tài)調(diào)用一個(gè)不存在的方法時(shí),例如Player::playOneSong(),這個(gè)魔術(shù)方法就會被調(diào)用。它通過getFacadeRoot()方法創(chuàng)建出一個(gè)對象,然后在這個(gè)對象上真正執(zhí)行我們的方法。
再看看getFacadeRoot()方法:
/**
* Get the root object behind the facade.
*
* @return mixed
*/
public static function getFacadeRoot()
{
return static::resolveFacadeInstance(static::getFacadeAccessor());
}
這里通過我們自定義門面類中的getFacadeAccessor方法,獲取到一個(gè)service_id(暫且這么叫吧),然后傳給resolveFacadeInstance方法。
再往下看resolveFacadeInstance方法:
/**
* Resolve the facade root instance from the container.
*
* @param string|object $name
* @return mixed
*/
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];
}
通過static::$app[$name]從服務(wù)容器中獲取 key 為name的對象,服務(wù)容器會幫我們實(shí)例化出對應(yīng)的對象(前提是已經(jīng)綁定好)。
服務(wù)容器$app是一個(gè)對象,但它實(shí)現(xiàn)了ArrayAccess接口,所以可以用這種數(shù)組的方式訪問。
獲取到對象后,放入到static::$resolvedInstance靜態(tài)變量中,這樣下次再獲取相同對象時(shí),就不用重復(fù)實(shí)例化了。
到此這篇關(guān)于PHP Laravel門面的實(shí)現(xiàn)原理詳解的文章就介紹到這了,更多相關(guān)PHP Laravel門面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP/Javascript/CSS/jQuery常用知識大全詳細(xì)整理
PHP/Javascript/CSS/jQuery常用知識大全詳細(xì)整理(原創(chuàng))感興趣的朋友可以參考下2013-01-01
php5.4傳引用時(shí)報(bào)錯(cuò)問題分析
這篇文章主要介紹了php5.4傳引用時(shí)報(bào)錯(cuò)問題,結(jié)合實(shí)例形式分析了php5.4傳引用時(shí)報(bào)錯(cuò)問題及解決方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-01-01
PHP面向?qū)ο蟪绦蛟O(shè)計(jì)之對象的遍歷操作示例
這篇文章主要介紹了PHP面向?qū)ο蟪绦蛟O(shè)計(jì)之對象的遍歷操作,結(jié)合具體實(shí)例形式分析了php面向?qū)ο蟪绦蛟O(shè)計(jì)中對象屬性遍歷的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2019-06-06
php將數(shù)據(jù)庫導(dǎo)出成excel的方法
有時(shí)寫程序時(shí)后臺要求把大量數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫中,比如考試成績、電話簿等一般都是存放在excel中的數(shù)據(jù),這時(shí)我們可把excel導(dǎo)出成csv文件,然后通過以下程序即可批量導(dǎo)入數(shù)據(jù)到數(shù)據(jù)庫中2010-05-05
PHP簡單實(shí)現(xiàn)數(shù)字分頁功能示例
這篇文章主要介紹了PHP簡單實(shí)現(xiàn)數(shù)字分頁功能,結(jié)合實(shí)例形式分析了php數(shù)字分頁相關(guān)的數(shù)學(xué)運(yùn)算與字符串操作相關(guān)技巧,需要的朋友可以參考下2016-08-08

