如何擴展Laravel

註冊服務

向容器中註冊服務

// 綁定服務
$container->bind('log', function(){
    return new Log();
});
// 綁定單例服務
$container->singleton('log', function(){
    return new Log();
});

擴展綁定

擴展已有服務

$container->extend('log', function(Log $log){
    return new RedisLog($log);
});

Manager

Manager實際上是一個工廠,它爲服務提供了驅動管理功能。

Laravel中的很多組件都使用了Manager,如:AuthCacheLogNotificationQueueRedis等等,每個組件都有一個xxxManager的管理器。我們可以通過這個管理器擴展服務。

比如,如果我們想讓Cache服務支持RedisCache驅動,那麼我們可以給Cache服務擴展一個redis驅動:

Cache::extend('redis', function(){
    return new RedisCache();
});

這時候,Cache服務就支持redis這個驅動了。現在,找到config/cache.php,把default選項的值改成redis。這時候我們再用Cache服務時,就會使用RedisCache驅動來使用緩存。

Macro和Mixin

有些情況下,我們需要給一個類動態增加幾個方法,Macro或者Mixin很好的解決了這個問題。

在Laravel底層,有一個名爲MacroableTrait,凡是引入了Macroable的類,都支持MacroMixin的方式擴展,比如RequestResponseSessionGuardViewTranslator等等。

Macroable提供了兩個方法,macromixinmacro方法可以給類增加一個方法,mixin是把一個類中的方法混合到Macroable類中。

舉個例子,比如我們要給Request類增加兩個方法。

使用macro方法時:

Request::macro('getContentType', function(){
    // 函數內的$this會指向Request對象
    return $this->headers->get('content-type');
});
Request::macro('hasField', function(){
    return !is_null($this->get($name));
});

$contentType = Request::getContentstType();
$hasPassword = Request::hasField('password');

使用mixin方法時:

class MixinRequest{
    
    public function getContentType(){
        // 方法內必須返回一個函數
        return function(){
            return $this->headers->get('content-type');
        };
    }
    
    public function hasField(){
        return function($name){
            return !is_null($this->get($name));
        };
    }
}

Request::mixin(new MixinRequest());

$contentType = Request::getContentType();
$hasPassword = Request::hasField('password');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章