向容器中注册服务php
// 绑定服务 $container->bind('log', function(){ return new Log(); }); // 绑定单例服务 $container->singleton('log', function(){ return new Log(); });
扩展已有服务redis
$container->extend('log', function(Log $log){ return new RedisLog($log); });
Manager其实是一个工厂,它为服务提供了驱动管理功能。缓存
Laravel中的不少组件都使用了Manager,如:Auth
、Cache
、Log
、Notification
、Queue
、Redis
等等,每一个组件都有一个xxxManager
的管理器。咱们能够经过这个管理器扩展服务。函数
好比,若是咱们想让Cache
服务支持RedisCache
驱动,那么咱们能够给Cache
服务扩展一个redis
驱动:this
Cache::extend('redis', function(){ return new RedisCache(); });
这时候,Cache
服务就支持redis
这个驱动了。如今,找到config/cache.php
,把default
选项的值改为redis
。这时候咱们再用Cache
服务时,就会使用RedisCache
驱动来使用缓存。code
有些状况下,咱们须要给一个类动态增长几个方法,Macro
或者Mixin
很好的解决了这个问题。对象
在Laravel底层,有一个名为Macroable
的Trait
,凡是引入了Macroable
的类,都支持Macro
和Mixin
的方式扩展,好比Request
、Response
、SessionGuard
、View
、Translator
等等。get
Macroable
提供了两个方法,macro
和mixin
,macro
方法能够给类增长一个方法,mixin
是把一个类中的方法混合到Macroable
类中。it
举个例子,好比咱们要给Request
类增长两个方法。io
使用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');