下面由laravel開發(fā)入門教程欄目給大家介紹神奇的 laravel 宏指令(macro),希望對需要的朋友有所幫助!
可曾有過想要的一項(xiàng)功能在 Laravel 中,但它又不是真實(shí)存在的?讓我來給你介紹一下 Laravel 宏指令。宏指令允許你添加自定義功能到 Laravel 的內(nèi)部組件里去。
讓我們以一個(gè)簡單的 Request 門面方法為例。
Request::macro('introduce',?function?($name)?{ ????echo?'Hello?'?.?$name?.?'!'; }); Request::introduce('Caleb');?//?outputs?"Hello?Caleb!"
一個(gè)更加實(shí)用的 Request 宏指令是用于檢測當(dāng)前的 TLD(頂級域:.com,.net,.org,.etc…)。
Request::macro('tldIs',?function?($tld)?{ ????return?Str::is('*.'?.?$tld,?$this->root()); }); Request::tldIs('com')?//?returns?true?for?app.com Request::tldIs('dev')?//?returns?false?for?app.com
你會(huì)注意到 Laravel 自動(dòng)綁定 $this 到 Request 的上線文中,而不是在一個(gè)已經(jīng)定義宏的類里。比如:
class?AppServiceProvider { ????public?function?boot() ????{ ????????Request::macro('context',?function?()?{ ????????????return?get_class($this); ????????} ????} ... Request::context();? //?returns?'IlluminatehttpRequest' //?instead?of?'AppAppServiceProvider'
讓我們看一個(gè)更高級的示例。此宏有條件地基于當(dāng)前 TLD 在模型上添加一個(gè) where 語句。
Builder::macro('whenTldMatches',?function($tld,?$callback)?{ ????if?(Request::tldIs($tld))?{ ????????call_user_func($callback->bindTo($this)); ????} ????return?$this; }); SomeModel::whenTldMatches('org',?function?()?{ ????$this->where('id',?'>',?5); })->get(); //?applies?->where()?在?app.org?上應(yīng)用,而不在?app.com?上應(yīng)用
我們應(yīng)該在哪里定義它們?
服務(wù)提供者為為您的應(yīng)用程序定義宏的好地方。AppProvidersAppServiceProvider boot() 是 I 一個(gè)很好的注入點(diǎn),但是它很快就變得臃腫。
下一步是創(chuàng)建一個(gè) AppProvidersMacrosServiceProvider 并注冊在 config/app.php 里。 如果某宏與之相關(guān),我可能會(huì)創(chuàng)建一個(gè) AppProvidersTldAwareServiceProvider 來容納所有與 TLD 相關(guān)的宏。
哪些組件是 Macroable?
宏可以再任何具有 Macroable 特性的類上定義。下面是一個(gè) Macroable 的門面和類的列表
門面
● Cache
●?File
●?Lang
●?Request
●?Response
●?Route
●?URL
Illuminate Classes
●?IlluminateCacheRepository
●?IlluminateconsoleSchedulingEvent
●?IlluminatedatabaseEloquentBuilder
●?IlluminateDatabaseEloquentRelation
●?IlluminateDatabaseQueryBuilder
●?IlluminateFilesystemFilesystem
●?IlluminateFoundationTestingTestResponse
●?IlluminateHttpRedirectResponse
●?IlluminateHttpRequest
●?IlluminateHttpUploadedFile
●?IlluminateRoutingResponseFactory
●?IlluminateRoutingRouter
●?IlluminateRoutingUrlGenerator
●?IlluminateSupportArr
●?IlluminateSupportCollection
●?IlluminateSupportStr
●?IlluminateTranslationTranslator
●?IlluminateValidationRule
動(dòng)手
如果您發(fā)現(xiàn)自己在整個(gè)系統(tǒng)中對 Laravel 組件重復(fù)執(zhí)行邏輯,請考慮使用宏以實(shí)現(xiàn)更好的表達(dá)和重用。相信我,非常饞。
祝您好運(yùn)!
更多l(xiāng)aravel框架技術(shù)文章,請?jiān)L問laravel開發(fā)教程!