這篇文章主要介紹了Laravel中Macroable宏指令的用法,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
百度百科的定義:
計算機科學裡的宏(Macro),是一種批次處理的稱謂。一般說來,巨集是一種規則或模式,或稱語法替換 ,用於說明某一特定輸入(通常是字串)如何根據預先定義的規則轉換成對應的輸出(通常也是字串)。這種替換在預編譯時進行,稱作巨集展開。
我一開始接觸宏是在大學上電腦基礎課程時,老師講office時說的。那時老師介紹宏操作時沒太在意,只記得這一操作很強大,它能讓日常工作變得更容易。
今天我們講講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; }
很簡單的程式碼,根據參數的註釋,$macro
可以傳一個閉包或對象,之所以可以傳對象,多虧了PHP中的魔術方法
class Father { // 通过增加魔术方法**__invoke**我们就可以把对象当做闭包来使用了。 public function __invoke() { echo __CLASS__; } } class Child { use \Illuminate\Support\Traits\Macroable; } // 增加了宏指令之后,我们就能调用 Child 对象中不存在的方法了 Child::macro('show', new Father); // 输出:Father (new Child)->show();
Macroable::mixin
方法
這個方法是把一個物件的方法的回傳結果注入到原始物件中
public static function mixin($mixin) { // 通过反射获取该对象中所有公开和受保护的方法 $methods = (new ReflectionClass($mixin))->getMethods( ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED ); foreach ($methods as $method) { // 设置方法可访问,因为受保护的不能在外部调用 $method->setAccessible(true); // 调用 macro 方法批量创建宏指令 static::macro($method->name, $method->invoke($mixin)); } } // 实际使用 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
可以將一個類別的方法綁定到巨集類別中。需要注意的就是,方法必須是傳回一個閉包類型。
Macroable::hasMacro
方法
public static function hasMacro($name) { return isset(static::$macros[$name]); }
這個方法就比較簡單沒什麼複雜可言,就判斷是否存在宏指令。通常是使用宏指令之前判斷一下。
Macroable::__call
和Macroable::__callStatic
方法
正是由於這兩個方法,我們才能進行巨集操作,兩個方法除了執行方式不同,程式碼大同小異。這裡講一下__call
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); } // 不是闭包,比如对象的时候,直接通过这种方法运行,但是要确保对象有`__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();
在上面的操作中我們綁定巨集時,在閉包中可以透過$this
來呼叫Child
的屬性,是因為在__call
方法中我們使用Closure::bindTo
方法。
官網對Closure::bindTo
的解釋:複製目前閉包對象,並綁定指定的$this物件和類別作用域。
Laravel 中對類別增加巨集指令
Laravel中很多類別都使用了巨集這個trait
#例如Illuminate\Filesystem\Filesystem::class
,我們想為這個類別增加一個方法,但不會動到裡面的程式碼。
-
我們只需要到
App\Providers\AppServiceProvider::register
方法增加巨集指令(你也可以專門新建一個服務提供者專門處理)
1.然後增加一個測試路由,測試我們新增加的方法
2.然後打開瀏覽器運行,你會發現,我們的程式碼可以正常的運行了並輸出結果了
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!
相關推薦:
以上是Laravel中Macroable巨集指令的用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版
SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。