如何扩展Laravel

注册服务

向容器中注册服务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

Manager其实是一个工厂,它为服务提供了驱动管理功能。缓存

Laravel中的不少组件都使用了Manager,如:AuthCacheLogNotificationQueueRedis等等,每一个组件都有一个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

有些状况下,咱们须要给一个类动态增长几个方法,Macro或者Mixin很好的解决了这个问题。对象

在Laravel底层,有一个名为MacroableTrait,凡是引入了Macroable的类,都支持MacroMixin的方式扩展,好比RequestResponseSessionGuardViewTranslator等等。get

Macroable提供了两个方法,macromixinmacro方法能够给类增长一个方法,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');
相关文章
相关标签/搜索