註冊服務
向容器中註冊服務
// 綁定服務
$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,如:Auth
、Cache
、Log
、Notification
、Queue
、Redis
等等,每個組件都有一個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底層,有一個名爲Macroable
的Trait
,凡是引入了Macroable
的類,都支持Macro
和Mixin
的方式擴展,比如Request
、Response
、SessionGuard
、View
、Translator
等等。
Macroable
提供了兩個方法,macro
和mixin
,macro
方法可以給類增加一個方法,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');