【问题标题】:how can i override cache "get" method laravel?我如何覆盖缓存“get”方法laravel?
【发布时间】:2021-10-11 15:31:32
【问题描述】:

我想重写 Illuminate\Cache\Repository 类的方法 get() 为:

<?php
namespace App\Illuminate\Cache;

use Illuminate\Cache\Repository as BaseRepository;

class Repository extends BaseRepository{

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

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

有什么办法吗?


编辑 1

我创建了一个macro(),但它仅在BaseRepository 中不存在该方法时才有效,例如:

这不起作用

use Illuminate\Cache;

Cache\Repository::macro('get',function (){
    return 'hi';
});

但是,这行得通:

use Illuminate\Cache;

Cache\Repository::macro('newName',function (){
    return 'hi';
});

所以macro 不能这样做,因为Laravel::macro() 正在创建一个新函数但没有覆盖

【问题讨论】:

    标签: php laravel laravel-8 laravel-cache


    【解决方案1】:

    当你创建新的缓存对象时,很容易从你的类中创建一个实例,而不是 BaseRepository 类。

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

    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Illuminate\Cache\Repository as BaseRepository;
    use App\Illuminate\Cache\Repository;
    
    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()
        {
            //
        }
    }
    

    但是您必须将 \Illuminate\Contracts\Cache\Store 的实现传递给存储库的构造函数。

    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;    
    use Illuminate\Cache\Repository as BaseRepository;
    use App\Repository;
    use Illuminate\Cache\ArrayStore;
    
    
    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()
        {
            //
        }
    }
    

    【讨论】:

    • 你好。你能详细解释一下情况吗?它会返回错误吗?是的,我知道它不起作用,因为您必须注意将 \Illuminate\Contracts\Cache\Store 实现之一作为 Repository 类中的依赖项传递。例如,我在答案的末尾添加了如何使用 ArrayStore 制作缓存存储库类。
    • 嗨@mahmood-moradian,谢谢..不幸的是redis驱动程序不会从新方法中读取“我试过dd($key),但是当我尝试dd( $key) 来自基本方法,我从 redis 驱动程序获取密钥
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2016-08-23
    • 1970-01-01
    • 2018-06-11
    • 2013-08-14
    相关资源
    最近更新 更多