佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > Laravel中簡(jiǎn)約卻不簡(jiǎn)單的Macroable宏指令詳解

Laravel中簡(jiǎn)約卻不簡(jiǎn)單的Macroable宏指令詳解

熱門標(biāo)簽:Mysql連接數(shù)設(shè)置 科大訊飛語(yǔ)音識(shí)別系統(tǒng) 團(tuán)購(gòu)網(wǎng)站 服務(wù)器配置 Linux服務(wù)器 電子圍欄 阿里云 銀行業(yè)務(wù)

百度百科的定義:

計(jì)算機(jī)科學(xué)里的宏(Macro),是一種批量處理的稱謂。一般說(shuō)來(lái),宏是一種規(guī)則或模式,或稱語(yǔ)法替換 ,用于說(shuō)明某一特定輸入(通常是字符串)如何根據(jù)預(yù)定義的規(guī)則轉(zhuǎn)換成對(duì)應(yīng)的輸出(通常也是字符串)。這種替換在預(yù)編譯時(shí)進(jìn)行,稱作宏展開。

我一開始接觸宏是在大學(xué)上計(jì)算機(jī)基礎(chǔ)課程時(shí),老師講office時(shí)說(shuō)的。那時(shí)老師介紹宏操作時(shí)沒(méi)太在意,只記得這一操作很強(qiáng)大,它能使日常工作變得更容易。

今天我們講講Laravel中的宏操作

首先完整的源碼

?php
 
namespace Illuminate\Support\Traits;
 
use Closure;
use ReflectionClass;
use ReflectionMethod;
use BadMethodCallException;
 
trait Macroable
{
 /**
 * The registered string macros.
 *
 * @var array
 */
 protected static $macros = [];
 
 /**
 * Register a custom macro.
 *
 * @param string $name
 * @param object|callable $macro
 *
 * @return void
 */
 public static function macro($name, $macro)
 {
 static::$macros[$name] = $macro;
 }
 
 /**
 * Mix another object into the class.
 *
 * @param object $mixin
 * @return void
 */
 public static function mixin($mixin)
 {
 $methods = (new ReflectionClass($mixin))->getMethods(
  ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
 );
 
 foreach ($methods as $method) {
  $method->setAccessible(true);
 
  static::macro($method->name, $method->invoke($mixin));
 }
 }
 
 /**
 * Checks if macro is registered.
 *
 * @param string $name
 * @return bool
 */
 public static function hasMacro($name)
 {
 return isset(static::$macros[$name]);
 }
 
 /**
 * Dynamically handle calls to the class.
 *
 * @param string $method
 * @param array $parameters
 * @return mixed
 *
 * @throws \BadMethodCallException
 */
 public static function __callStatic($method, $parameters)
 {
 if (! static::hasMacro($method)) {
  throw new BadMethodCallException("Method {$method} does not exist.");
 }
 
 if (static::$macros[$method] instanceof Closure) {
  return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
 }
 
 return call_user_func_array(static::$macros[$method], $parameters);
 }
 
 /**
 * Dynamically handle calls to the class.
 *
 * @param string $method
 * @param array $parameters
 * @return mixed
 *
 * @throws \BadMethodCallException
 */
 public function __call($method, $parameters)
 {
 if (! static::hasMacro($method)) {
  throw new BadMethodCallException("Method {$method} does not exist.");
 }
 
 $macro = static::$macros[$method];
 
 if ($macro instanceof Closure) {
  return call_user_func_array($macro->bindTo($this, static::class), $parameters);
 }
 
 return call_user_func_array($macro, $parameters);
 }
}

Macroable::macro方法

public static function macro($name, $macro)
{
 static::$macros[$name] = $macro;
}

很簡(jiǎn)單的代碼,根據(jù)參數(shù)的注釋,$macro可以傳一個(gè)閉包或者對(duì)象,之所以可以傳對(duì)象,多虧了PHP中的魔術(shù)方法

class Father
{
 // 通過(guò)增加魔術(shù)方法**__invoke**我們就可以把對(duì)象當(dāng)做閉包來(lái)使用了。
 public function __invoke()
 {
 echo __CLASS__;
 }
}
 
class Child
{
 use \Illuminate\Support\Traits\Macroable;
}
 
// 增加了宏指令之后,我們就能調(diào)用 Child 對(duì)象中不存在的方法了
Child::macro('show', new Father);
// 輸出:Father
(new Child)->show();

Macroable::mixin方法

這個(gè)方法是把一個(gè)對(duì)象的方法的返回結(jié)果注入到原對(duì)象中

public static function mixin($mixin)
{
 // 通過(guò)反射獲取該對(duì)象中所有公開和受保護(hù)的方法
 $methods = (new ReflectionClass($mixin))->getMethods(
  ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
 );
 
 foreach ($methods as $method) {
  // 設(shè)置方法可訪問(wèn),因?yàn)槭鼙Wo(hù)的不能在外部調(diào)用
  $method->setAccessible(true);
 
  // 調(diào)用 macro 方法批量創(chuàng)建宏指令
  static::macro($method->name, $method->invoke($mixin));
 }
}
 
// 實(shí)際使用
class Father
{
 public function say()
 {
  return function () {
   echo 'say';
  };
 }
 
 public function show()
 {
  return function () {
   echo 'show';
  };
 }
 
 protected function eat()
 {
  return function () {
   echo 'eat';
  };
 }
}
 
class Child
{
 use \Illuminate\Support\Traits\Macroable;
}
 
// 批量綁定宏指令
Child::mixin(new Father);
 
$child = new Child;
// 輸出:say
$child->say();
// 輸出:show
$child->show();
// 輸出:eat
$child->eat();

在上面的代碼可以看出mixin可以將一個(gè)類的方法綁定到宏類中。需要注意的就是,方法必須是返回一個(gè)閉包類型。

* Macroable::hasMacro方法

public static function hasMacro($name)
{
 return isset(static::$macros[$name]);
}

這個(gè)方法就比較簡(jiǎn)單沒(méi)什么復(fù)雜可言,就判斷是否存在宏指令。通常是使用宏指令之前判斷一下。

* Macroable::__call和Macroable::__callStatic方法

正是由于這兩個(gè)方法,我們才能進(jìn)行宏操作,兩個(gè)方法除了執(zhí)行方式不同,代碼大同小異。這里講一下__call

public function __call($method, $parameters)
{
 // 如果不存在這個(gè)宏指令,直接拋出異常
 if (! static::hasMacro($method)) {
  throw new BadMethodCallException("Method {$method} does not exist.");
 }
 
 // 得到存儲(chǔ)的宏指令
 $macro = static::$macros[$method];
 
 // 閉包做一點(diǎn)點(diǎn)特殊的處理
 if ($macro instanceof Closure) {
  return call_user_func_array($macro->bindTo($this, static::class), $parameters);
 }
 
 // 不是閉包,比如對(duì)象的時(shí)候,直接通過(guò)這種方法運(yùn)行,但是要確保對(duì)象有`__invoke`方法
 return call_user_func_array($macro, $parameters);
}
 
 
class Child
{
 use \Illuminate\Support\Traits\Macroable;
 
 protected $name = 'father';
}
 
// 閉包的特殊處理,需要做的就是綁定 $this, 如
Child::macro('show', function () {
 echo $this->name;
});
 
// 輸出:father
(new Child)->show();

在上面的操作中我們綁定宏時(shí),在閉包中可以通過(guò)$this來(lái)調(diào)用Child的屬性,是因?yàn)樵赺_call方法中我們使用Closure::bindTo方法。

官網(wǎng)對(duì)Closure::bindTo的解釋:復(fù)制當(dāng)前閉包對(duì)象,綁定指定的$this對(duì)象和類作用域。

Laravel 中對(duì)類增加宏指令

Laravel中很多類都使用了宏這個(gè)trait

比如Illuminate\Filesystem\Filesystem::class,我們想為這個(gè)類增加一個(gè)方法,但不會(huì)動(dòng)到里面的代碼。

1. 我們只需要到App\Providers\AppServiceProvider::register方法增加宏指令(你也可以專門新建一個(gè)服務(wù)提供者專門處理)


2. 然后增加一條測(cè)試路由,測(cè)試我們新增加的方法

3. 然后打開瀏覽器運(yùn)行,你就會(huì)發(fā)現(xiàn),我們的代碼可以正常的運(yùn)行了并輸出結(jié)果了

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

標(biāo)簽:棗莊 萍鄉(xiāng) 廣元 衡水 江蘇 衢州 蚌埠 大理

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel中簡(jiǎn)約卻不簡(jiǎn)單的Macroable宏指令詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    海丰县| 定结县| 社旗县| 罗平县| 同德县| 敦煌市| 华宁县| 麻城市| 石门县| 衢州市| 高台县| 镇雄县| 齐河县| 临夏县| 眉山市| 辽源市| 葵青区| 浮梁县| 遵义市| 伽师县| 桐乡市| 汉寿县| 宜兰市| 巴彦淖尔市| 蒙山县| 康定县| 泗水县| 年辖:市辖区| 兴和县| 西乌| 永城市| 麻城市| 宁安市| 广灵县| 托克逊县| 揭阳市| 彭泽县| 大足县| 富蕴县| 大名县| 上饶县|