まあ、私はいくつか混乱した後、私は私が私が分かち合うと思った自分のための解決策を考え出した。
私は実際のUser
オブジェクトをキャッシュすることをあきらめ、通常のように認証を行い、ユーザーの関係をキャッシュしようとします。私のロジックがモデルであるので、これは、それを行うにはかなり汚いやり方のように感じている:私は内部のいくつかのメソッドを持っていたので、私の場合は
class User extends Model
{
// ..
/**
* This is the relationship I want to cache
*/
public function related()
{
return $this->hasMany(Related::class);
}
/**
* This method can be used when we want to utilise a cache
*/
public function getRelated()
{
return \Cache::remember("relatedByUser({$this->id})", 60, function() {
return $this->related;
});
}
/**
* Do something with the cached relationship
*/
public function totalRelated()
{
return $this->getRelated()->count();
}
}
、私はUser
モデル内の関連項目をキャッシュできるようにするために必要なその関係を使用するユーザー。上記のtotalRelated
メソッドのかなり簡単な例のように(私のプロジェクトはもう少し複雑です)。もちろん
、私は私のUser
モデルのような内部メソッドを持っていなかった場合、(例えば、コントローラで)
class MyController extends Controller
{
public function index()
{
$related = \Cache::remember("relatedByUser({$this->user->id})", 60, function() {
return $this->user->related;
});
// Do something with the $related items...
}
}
というのが私のモデルとキャッシュ外部からの関係を呼び出すことも簡単だっただろう
もう一度、これは私にとって最高の解決策ではないと感じています。私は他の提案を試みています。
乾杯
編集:私はさらに一歩行って、キャッシュの関係を支援するために私の親Model
クラスのメソッドのカップルを実装し、受け入れるすべての私relatonshipsのgetterメソッドを実装しました$useCache
パラメータ、物事はもう少し柔軟にします
親モデルクラス:
class Model extends BaseModel
{
/**
* Helper method to get a value from the cache if it exists, or using the provided closure, caching the result for
* the default cache time.
*
* @param $key
* @param Closure|null $callback
* @return mixed
*/
protected function cacheRemember($key, Closure $callback = null)
{
return Cache::remember($key, Cache::getDefaultCacheTime(), $callback);
}
/**
* Another helper method to either run a closure to get a value, or if useCache is true, attempt to get the value
* from the cache, using the provided key and the closure as a means of getting the value if it doesn't exist.
*
* @param $useCache
* @param $key
* @param Closure $callback
* @return mixed
*/
protected function getOrCacheRemember($useCache, $key, Closure $callback)
{
return !$useCache ? $callback() : $this->cacheRemember($key, $callback);
}
}
マイUserクラス:
class User extends Model
{
public function related()
{
return $this->hasMany(Related::class);
}
public function getRelated($useCache = false)
{
return $this->getOrCacheRemember($useCache, "relatedByUser({$this->id})", function() {
return $this->related;
});
}
}
使用法:
$related = $user->getRelated(); // Gets related from the database
$relatedTwo = $user->getRelated(true); // Gets related from the cache if present (Or from database and caches result)