亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

在 Laravel 中為查詢快取建立不同的鍵
P粉739886290
P粉739886290 2024-03-19 18:16:10
0
2
623

我在一個專案中使用了儲存庫來快取所有查詢。

有一個 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 ...
}

然後我在我的服務(wù)中使用了這個儲存庫

郵政服務(wù):

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筆最新記錄?,F(xiàn)在我需要為所有儲存庫查詢建立一個唯一的 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);
    });
}

這很好。但問題是這段程式碼在該類別的所有方法中重複。 如果我在另一個類別中使用此程式碼,方法名稱將不正確。 您有什麼建議來防止重複此程式碼?

P粉739886290
P粉739886290

全部回覆(2)
P粉401901266

我透過將函數(shù)名稱傳遞給另一個類別來解決這個問題

我建立了 CacheKey 類別:

class CacheKey{

    public static function generate(Model $model, $functionName):string
    {
        return $model->getTable()."_".$functionName;
    }
}

然後在儲存庫的任何方法中我們都可以使用這個輔助類,如下所示:

$cacheKey = CacheKey::generate($this->model,__FUNCTION__);??
P粉287726308

你可以用這種方式輕鬆使用魔術(shù)方法:

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);
        });
    }

}
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板