如何覆盖缓存获取方法laravel? [英] how can i override cache "get" method laravel?

查看:40
本文介绍了如何覆盖缓存获取方法laravel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将类IlluminateCacheRepository的方法get()重写为:

<?php
namespace AppIlluminateCache;

use IlluminateCacheRepository as BaseRepository;

class Repository extends BaseRepository{

    public function get($key)
    {
        // changes
    }
}

但我不知道如何告诉Laravel加载我的类而不是原始类。

有什么方法可以做到这一点吗?


编辑%1

我已经创建了一个macro(),但它只有在BaseRepository中不存在该方法时才起作用,例如:

此操作不起作用

use IlluminateCache;

CacheRepository::macro('get',function (){
    return 'hi';
});

但是,此操作奏效了:

use IlluminateCache;

CacheRepository::macro('newName',function (){
    return 'hi';
});

因此macro无法执行此操作,因为Laravel::macro()正在创建新函数,但未覆盖

推荐答案

创建新缓存对象时,很容易从您的类创建实例,而不是从BaseRepository类创建。

但是,当Laravel的服务容器生成对象(或使用依赖项注入)时,您必须将扩展类绑定为appServiceProvider中的主类。

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateCacheRepository as BaseRepository;
use AppIlluminateCacheRepository;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(BaseRepository::class, function ($app) {
            return $app->make(Repository::class);
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

但是您必须将IlllightateContractsCacheStore的实现传递给存储库的构造函数。

namespace AppProviders;

use IlluminateSupportServiceProvider;    
use IlluminateCacheRepository as BaseRepository;
use AppRepository;
use IlluminateCacheArrayStore;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(BaseRepository::class,function($app){
            return $app->make(Repository::class,['store'=>$app->make(ArrayStore::class)]);
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

这篇关于如何覆盖缓存获取方法laravel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆