在与Laravel 5.6的关系上打破缓存

问题描述 投票:1回答:1

我有一个名为Tournament的模型,其中每个Tournament都被缓存了一些关系,使用每个模型的密钥(即tournament.1)。

return \Cache::remember('tournament.' . $id, 60*24*7, function() use ($id) {
    return Tournament::where('id', $id)
        ->with(['prizes', 'sponsor'])
        ->firstOrFail();
});

当我更新关系时,我想忘记锦标赛的关键。我知道我可以使用这样的事件:

public static function boot()
{
    static::saving(function ($prize) {
        \Cache::forget('tournament.' . $prize->tournament->id);
    });

    return parent::boot();
}

但是,这样做意味着我必须为所有其他关系重复此代码。我可能会为此创建一个特征,但有没有更好的方法来实现我想要实现的目标?

laravel
1个回答
0
投票

我最终用一个特征来解决这个问题。

namespace App\Traits;

trait ShouldCacheBust
{
/**
 * The "booting" method of the model.
 */
public static function boot()
{
    static::saving(function ($model) {
        $cacheKey = static::cacheBustKey($model);

        if ($cacheKey) {
            \Cache::forget($cacheKey);
        }
    });

    return parent::boot();
}

/**
 * Return the key to be removed from Cache
 * 
 * @param Model $model
 * @return string|null
 */
abstract public function cacheBustKey(Model $model);
}

然后像这样使用它:

/**
 * Return the key to be removed from Cache
 *
 * @param Model $model
 * @return mixed|string
 */
public static function cacheBustKey(Model $model)
{
    return 'tournament.' . $model->id;
}
© www.soinside.com 2019 - 2024. All rights reserved.