Laravel Cache
GitHub概要
laravel/framework
The Laravel Framework.
スター33,844
ウォッチ958
フォーク11,444
作成日:2013年1月10日
言語:PHP
ライセンス:MIT License
トピックス
frameworklaravelphp
スター履歴
データ取得日時: 2025/7/19 09:31
キャッシュライブラリ
Laravel Cache
概要
Laravel CacheはPHPのLaravelフレームワークに組み込まれたキャッシュシステムで、複数のキャッシュバックエンド(Redis、Memcached、ファイル、データベース等)を統一APIで操作できます。
詳細
Laravel CacheはLaravelフレームワークの核心機能の一つで、アプリケーションのパフォーマンス向上を目的としたキャッシュソリューションです。Redis、Memcached、ファイルベース、データベース、配列(メモリ)など多様なキャッシュドライバーをサポートし、設定ファイルで簡単に切り替えできます。Cacheファサードを通じて直感的なAPIを提供し、get、put、forever、forget、incrementなどの基本操作から、remember、rememberForever等の高レベル関数まで充実しています。タグベースキャッシュによりグループ化されたデータの一括操作、複数ストアの同時利用、カスタムドライバーの実装も可能です。Laravelエコシステムとの完全統合により、Eloquentクエリキャッシュ、ビューキャッシュ、ルートキャッシュなど様々なレベルでのキャッシュが自動的に機能します。artisanコマンドによるキャッシュ管理、設定値キャッシュ、セッションキャッシュなど、フレームワーク全体の高速化に貢献しています。
メリット・デメリット
メリット
- 統一API: 複数のキャッシュバックエンドを同じインターフェースで操作
- 豊富なドライバー: Redis、Memcached、ファイル、DB、配列サポート
- フレームワーク統合: Laravelエコシステムとの完全統合
- ファサードパターン: 簡潔で直感的なAPI設計
- タグベースキャッシュ: グループ化されたキャッシュの効率的管理
- artisanコマンド: コマンドラインからの簡単なキャッシュ管理
- 豊富な機能: TTL、増減操作、条件付きキャッシュ等
デメリット
- Laravel依存: Laravel フレームワーク外では使用不可
- PHP限定: PHP以外の言語では利用できない
- 設定の複雑さ: 複数ストア使用時の設定が複雑
- パフォーマンス: ファサード使用による若干のオーバーヘッド
- デバッグの困難さ: キャッシュ関連の問題のデバッグが困難な場合がある
主要リンク
- Laravel Cache公式ドキュメント
- Laravel公式サイト
- Laravel Facades ドキュメント
- Laravel GitHub リポジトリ
- Packagist Laravel Cache
書き方の例
基本的な設定(config/cache.php)
<?php
// config/cache.php
return [
// デフォルトキャッシュストア
'default' => env('CACHE_DRIVER', 'redis'),
// キャッシュストア設定
'stores' => [
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
],
// キャッシュキープレフィックス
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];
基本的なキャッシュ操作
<?php
use Illuminate\Support\Facades\Cache;
class CacheExampleController extends Controller
{
public function basicOperations()
{
// データの保存
Cache::put('key', 'value', 600); // 600秒間有効
Cache::put('user:123', ['name' => 'John', 'email' => '[email protected]'], now()->addHours(1));
// データの取得
$value = Cache::get('key');
$user = Cache::get('user:123');
// デフォルト値付きでの取得
$setting = Cache::get('app_setting', 'default_value');
// データの存在確認
if (Cache::has('key')) {
echo "Key exists in cache";
}
// データの削除
Cache::forget('key');
// すべてのキャッシュクリア
Cache::flush();
// 永続キャッシュ(期限なし)
Cache::forever('permanent_data', 'important_value');
// 数値の増減
Cache::increment('page_views');
Cache::decrement('remaining_items', 5);
return response()->json(['status' => 'Cache operations completed']);
}
}
remember/rememberForever の使用
<?php
use Illuminate\Support\Facades\Cache;
use App\Models\User;
class UserService
{
public function getUserProfile($userId)
{
// キャッシュから取得、存在しない場合はDBから取得してキャッシュに保存
return Cache::remember("user_profile_{$userId}", 3600, function () use ($userId) {
return User::with(['profile', 'preferences'])
->find($userId)
->toArray();
});
}
public function getPopularPosts()
{
// 永続キャッシュ版
return Cache::rememberForever('popular_posts', function () {
return Post::where('views', '>', 1000)
->orderBy('views', 'desc')
->take(10)
->get();
});
}
public function getUserSettings($userId)
{
$cacheKey = "user_settings_{$userId}";
// pull: キャッシュから取得して即座に削除
return Cache::pull($cacheKey, function () use ($userId) {
return UserSetting::where('user_id', $userId)->first();
});
}
public function getApiData($endpoint)
{
return Cache::remember("api_data_{$endpoint}", 1800, function () use ($endpoint) {
// 外部APIからデータ取得
$response = Http::get("https://api.example.com/{$endpoint}");
return $response->json();
});
}
}
複数ストアの使用
<?php
use Illuminate\Support\Facades\Cache;
class MultiStoreService
{
public function demonstrateMultipleStores()
{
// デフォルトストア使用
Cache::put('default_key', 'default_value', 600);
// 特定のストア使用
Cache::store('redis')->put('redis_key', 'redis_value', 600);
Cache::store('memcached')->put('memcached_key', 'memcached_value', 600);
Cache::store('file')->put('file_key', 'file_value', 600);
// 各ストアからデータ取得
$defaultValue = Cache::get('default_key');
$redisValue = Cache::store('redis')->get('redis_key');
$memcachedValue = Cache::store('memcached')->get('memcached_key');
$fileValue = Cache::store('file')->get('file_key');
return [
'default' => $defaultValue,
'redis' => $redisValue,
'memcached' => $memcachedValue,
'file' => $fileValue,
];
}
public function sessionCaching()
{
// セッション専用キャッシュストアの使用
$sessionStore = Cache::store('session');
$sessionStore->put('user_cart', ['item1', 'item2'], 7200);
return $sessionStore->get('user_cart', []);
}
}
タグベースキャッシュ
<?php
use Illuminate\Support\Facades\Cache;
class TaggedCacheService
{
public function useTaggedCache()
{
// タグ付きキャッシュの保存
Cache::tags(['users', 'posts'])->put('user_posts_123', $postsData, 3600);
Cache::tags(['users'])->put('user_profile_123', $profileData, 3600);
Cache::tags(['posts'])->put('recent_posts', $recentPosts, 1800);
// タグ付きキャッシュの取得
$userPosts = Cache::tags(['users', 'posts'])->get('user_posts_123');
$userProfile = Cache::tags(['users'])->get('user_profile_123');
// 特定タグのキャッシュをすべて削除
Cache::tags(['posts'])->flush(); // 投稿関連のキャッシュをすべて削除
Cache::tags(['users'])->flush(); // ユーザー関連のキャッシュをすべて削除
return [
'user_posts' => $userPosts,
'user_profile' => $userProfile,
];
}
public function cacheInvalidation($userId)
{
// ユーザー関連のキャッシュを一括削除
Cache::tags(['users', "user_{$userId}"])->flush();
// 部分的なタグキャッシュ削除
Cache::tags(['products', 'category_electronics'])->flush();
}
}
Eloquentモデルキャッシュ統合
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Product extends Model
{
protected $fillable = ['name', 'price', 'category_id', 'description'];
// モデルイベントでキャッシュ管理
protected static function boot()
{
parent::boot();
static::saved(function ($product) {
// 商品更新時にキャッシュクリア
Cache::tags(['products', "product_{$product->id}"])->flush();
Cache::forget("category_products_{$product->category_id}");
});
static::deleted(function ($product) {
// 商品削除時にキャッシュクリア
Cache::tags(['products', "product_{$product->id}"])->flush();
});
}
// キャッシュ付きスコープ
public function scopeCached($query, $key, $minutes = 60)
{
return Cache::remember($key, $minutes * 60, function () use ($query) {
return $query->get();
});
}
// カテゴリ別商品のキャッシュ取得
public static function getCachedByCategory($categoryId)
{
return Cache::remember("category_products_{$categoryId}", 3600, function () use ($categoryId) {
return static::where('category_id', $categoryId)
->with('category')
->orderBy('created_at', 'desc')
->get();
});
}
}
class ProductController extends Controller
{
public function index()
{
// キャッシュされた商品一覧
$products = Cache::remember('all_products', 3600, function () {
return Product::with('category')->paginate(20);
});
return view('products.index', compact('products'));
}
public function show($id)
{
$product = Cache::remember("product_detail_{$id}", 7200, function () use ($id) {
return Product::with(['category', 'reviews'])->findOrFail($id);
});
return view('products.show', compact('product'));
}
}
カスタムキャッシュドライバー
<?php
use Illuminate\Cache\CacheManager;
use Illuminate\Support\ServiceProvider;
class CustomCacheServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->resolving('cache', function (CacheManager $cache) {
$cache->extend('custom', function ($app, $config) {
return new CustomCacheStore($config);
});
});
}
}
class CustomCacheStore implements \Illuminate\Contracts\Cache\Store
{
protected $config;
public function __construct($config)
{
$this->config = $config;
}
public function get($key)
{
// カスタム取得ロジック
return $this->retrieveFromCustomSource($key);
}
public function put($key, $value, $seconds)
{
// カスタム保存ロジック
return $this->storeToCustomSource($key, $value, $seconds);
}
public function forget($key)
{
// カスタム削除ロジック
return $this->deleteFromCustomSource($key);
}
public function flush()
{
// カスタムフラッシュロジック
return $this->clearCustomSource();
}
public function getPrefix()
{
return $this->config['prefix'] ?? '';
}
// その他必要なメソッドの実装...
}
artisanコマンドとキャッシュ管理
# キャッシュクリア
php artisan cache:clear
# 設定キャッシュ
php artisan config:cache
php artisan config:clear
# ルートキャッシュ
php artisan route:cache
php artisan route:clear
# ビューキャッシュ
php artisan view:cache
php artisan view:clear
# すべてのキャッシュを最適化
php artisan optimize
php artisan optimize:clear