LoginSignup
10
10

More than 5 years have passed since last update.

illuminate/CacheをLaravelフレームワークの外で使う方法

Last updated at Posted at 2015-05-27

Laravelのilluminateはコンポーネント化されていて、PHPでちょっとしたプログラムを書くときや、Wordpressのプラグイン作る時とかcomposerでインストールして使うと便利ですよね。

今回はilluminate/Cacheを単独で使おうとした時に、4.x時代と使い方が変わっていたのでそのメモです。

まずはcomposerにrequire

composer require illuminate/cache:5.0.* illuminate/filesystem:5.0.*

適切な場所でvendor/autoload.phpのインクルードも忘れずに。

require 'vendor/autoload.php';

Laravel4系のilluminate/Cacheまで

CacheManagerのコンストラクタに配列で設定すればOKでした。

$app = [
    'config' => [
        'cache.driver' => 'file',
        'cache.path' => 'path/to/your/cachedir'
        'cache.prefix' => 'your_app_name'
    ]
];

$cacheManager = new CacheManager($app);
$cache = $cacheManager->driver();

$cache->put(/* stuff */);

Laravel5系のilluminate/Cache

CacheManagerのコンストラクタにコンテナを設定してあげる必要があります。

$app = new Illuminate\Container\Container();
$app->singleton('files', function () {
    return new Illuminate\Filesystem\Filesystem();
});
$app->singleton('config', function () {
    return ['cache.default' => 'files', 'cache.stores.files' => ['driver' => 'file', 'path' => 'path/to/your/cachedir']];
});

$cacheManager = new CacheManager($app);
$cache = $cacheManager->driver();

$cache->put('test', 'stuff', 5);

キャッシュドライバを限定して使うならもっとシンプルに

$filestore = new \Illuminate\Cache\FileStore(new \Illuminate\Filesystem\Filesystem(), 'path/to/your/cachedir');
$cache = new \Illuminate\Cache\Repository($filestore);

$cache->put('test', 'stuff', 5);

同じ要領で DB, Memcached, Redisがキャッシュドライバとして使えるかと思います。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10