緩存用法

2018-02-24 15:52 更新

保存對象到緩存中

Cache::put('key', 'value', $minutes);

使用 Carbon 對象配置緩存過期時間

$expiresAt = Carbon::now()->addMinutes(10);

Cache::put('key', 'value', $expiresAt);

若是對象不存在,則將其存入緩存中

Cache::add('key', 'value', $minutes);

當(dāng)對象確實被加入緩存時,使用 add 方法將會返回 true 否則會返回 false 。

確認(rèn)對象是否存在

if (Cache::has('key'))
{
    //
}

從緩存中取得對象

$value = Cache::get('key');

取得對象或是返回默認(rèn)值

$value = Cache::get('key', 'default');

$value = Cache::get('key', function() { return 'default'; });

永久保存對象到緩存中

Cache::forever('key', 'value');

有時候您會希望從緩存中取得對象,而當(dāng)此對象不存在時會保存一個默認(rèn)值,您可以使用 Cache::remember 方法:

$value = Cache::remember('users', $minutes, function()
{
    return DB::table('users')->get();
});

您也可以結(jié)合 remember 和 forever 方法:

$value = Cache::rememberForever('users', function()
{
    return DB::table('users')->get();
});

請注意所有保存在緩存中的對象皆會被序列化,所以您可以任意保存各種類型的數(shù)據(jù)。

從緩存拉出對象

如果您需要從緩存中取得對象后將它刪除,您可以使用 pull 方法:

$value = Cache::pull('key');

從緩存中刪除對象

Cache::forget('key');

獲取特定的緩存存儲

當(dāng)使用多種緩存存儲時,你可以通過 store 方法來訪問它們:

$value = Cache::store('foo')->get('key');

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號