我在一个项目中使用了存储库来缓存所有查询。
有一个 BaseRepository。
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class BaseRepository implements BaseRepositoryInterface{
    protected $model;
    protected int $cacheDuration = 600; //per seconds
    public function __construct(Model $model)
    {
        return $this->model = $model;
    }
    public function paginate(int $paginate,string $cacheKey)
    {
        return Cache::remember($cacheKey,$this->cacheDuration , function () use ($paginate) {
            return $this->model->latest()->paginate($paginate);
        });
    }
    // other methods ...
}
然后我在我的服务中使用了这个存储库
邮政服务:
use Illuminate\Support\Facades\App;
class PostService{
    public PostRepositoryInterface $postRepository;
    public function __construct()
    {
        $this->postRepository = App::make(PostRepositoryInterface::class);
    }
    public function paginate(int $paginate, string $cacheKey)
    {
        return $this->postRepository->paginate($paginate,$cacheKey);
    }
}
最后我在控制器中使用了 PostService
后控制器:
class PostController extends Controller{
    public PostService $postService;
    public function __construct()
    {
        $this->postService = App::make(PostService::class);
    }
    public function index()
    {
        string $cacheKey = "posts.paginate";
        return $this->postService->paginate(10);
    }
}
index方法将正确返回前10条最新记录。现在我需要为所有存储库查询创建一个唯一的 CacheKey。例如
TableName concat FunctionName // posts.paginate
所以我可以在存储库的所有方法中使用此代码
public function paginate(int $paginate)
{
    $cacheKey = $this->model->getTable().__FUNCTION__;
    return Cache::remember($cacheKey,$this->cacheDuration , function () use ($paginate) {
        return $this->model->latest()->paginate($paginate);
    });
}
这很好。但问题是这段代码在该类的所有方法中重复。 如果我在另一个类中使用此代码,方法名称将不正确。 您有什么建议来防止重复此代码?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我通过将函数名称传递给另一个类来解决这个问题
我创建了 CacheKey 类:
class CacheKey{ public static function generate(Model $model, $functionName):string { return $model->getTable()."_".$functionName; } }然后在存储库的任何方法中我们都可以使用这个辅助类,如下所示:
你可以通过这种方式轻松使用魔术方法:
class CacheService { private const $cacheableMethods = ['paginate']; private $otherSerivce; public __construct($otherSerivce) { $this->otherSerivce = $otherSerivce; } public __get($method, $args) { if(!in_array($method, static::$cachableMethods)) { return $this->otherSerivce->{$method}(...$args); } return Cache::remember(implode([$method, ...$args], ':'), function () { return $this->otherSerivce->{$method}(...$args); }); } }