Professional Documents
Culture Documents
Cache: Configuration
Cache: Configuration
Configuration
Driver Prerequisites
Cache Usage
Configuration
Laravel provides an expressive, unified API for various caching
backends. The cache configuration is located at config/cache.php . In
this file you may specify which cache driver you would like to be used
by default throughout your application. Laravel supports popular
caching backends like Memcached and Redis out of the box.
The cache configuration file also contains various other options, which
are documented within the file, so make sure to read over these
options. By default, Laravel is configured to use the file cache driver,
which stores the serialized, cached objects in the filesystem. For larger
applications, it is recommended that you use a more robust driver
such as Memcached or Redis. You may even configure multiple cache
configurations for the same driver.
Driver Prerequisites
Database
When using the database cache driver, you will need to setup a table
to contain the cache items. You'll find an example Schema declaration
for the table below:
{tip} You may also use the php artisan cache:table Artisan
command to generate a migration with the proper schema.
Memcached
Using the Memcached driver requires the Memcached PECL package
to be installed. You may list all of your Memcached servers in the
config/cache.php configuration file:
1 'memcached' => [
2 [
3 'host' => '127.0.0.1',
4 'port' => 11211,
5 'weight' => 100
6 ],
7 ],
You may also set the host option to a UNIX socket path. If you do this,
the port option should be set to 0 :
1 'memcached' => [
2 [
3 'host' => '/var/run/memcached/memcached.sock',
4 'port' => 0,
5 'weight' => 100
6 ],
7 ],
Redis
Before using a Redis cache with Laravel, you will need to either install
the PhpRedis PHP extension via PECL or install the predis/predis
package (~1.0) via Composer.
Cache Usage
However, you may also use the Cache facade, which is what we will
use throughout this documentation. The Cache facade provides
convenient, terse access to the underlying implementations of the
Laravel cache contracts:
1 <?php
2
3 namespace App\Http\Controllers;
4
5 use Illuminate\Support\Facades\Cache;
6
7 class UserController extends Controller
8 {
9 /**
10 * Show a list of all users of the application.
11 *
12 * @return Response
13 */
14 public function index()
15 {
16 $value = Cache::get('key');
17
18 //
19 }
20 }
1 $value = Cache::store('file')->get('foo');
2
3 Cache::store('redis')->put('bar', 'baz', 600); // 10
Minutes
1 $value = Cache::get('key');
2
3 $value = Cache::get('key', 'default');
You may even pass a Closure as the default value. The result of the
Closure will be returned if the specified item does not exist in the
cache. Passing a Closure allows you to defer the retrieval of default
values from a database or other external service:
1 if (Cache::has('key')) {
2 //
3 }
1 Cache::increment('key');
2 Cache::increment('key', $amount);
3 Cache::decrement('key');
4 Cache::decrement('key', $amount);
Sometimes you may wish to retrieve an item from the cache, but also
store a default value if the requested item doesn't exist. For example,
you may wish to retrieve all users from the cache or, if they don't exist,
retrieve them from the database and add them to the cache. You may
do this using the Cache::remember method:
1 $value = Cache::remember('users', $seconds, function ()
{
2 return DB::table('users')->get();
3 });
If the item does not exist in the cache, the Closure passed to the
remember method will be executed and its result will be placed in the
cache.
1 $value = Cache::pull('key');
If the storage time is not passed to the put method, the item will be
stored indefinitely:
1 Cache::put('key', 'value');
1 Cache::forever('key', 'value');
{tip} If you are using the Memcached driver, items that are stored
"forever" may be removed when the cache reaches its size limit.
1 Cache::forget('key');
You may clear the entire cache using the flush method:
1 Cache::flush();
{note} Flushing the cache does not respect the cache prefix and
will remove all entries from the cache. Consider this carefully
when clearing a cache which is shared by other applications.
Atomic Locks
{note} To utilize this feature, your application must be using the
memcached , dynamodb , or redis cache driver as your
application's default cache driver. In addition, all servers must be
communicating with the same central cache server.
1 use Illuminate\Support\Facades\Cache;
2
3 $lock = Cache::lock('foo', 10);
4
5 if ($lock->get()) {
6 // Lock acquired for 10 seconds...
7
8 $lock->release();
9 }
The get method also accepts a Closure. After the Closure is executed,
Laravel will automatically release the lock:
1 Cache::lock('foo')->get(function () {
2 // Lock acquired indefinitely and automatically
released...
3 });
If the lock is not available at the moment you request it, you may
instruct Laravel to wait for a specified number of seconds. If the lock
can not be acquired within the specified time limit, an
Illuminate\Contracts\Cache\LockTimeoutException will be
thrown:
1 use Illuminate\Contracts\Cache\LockTimeoutException;
2
3 $lock = Cache::lock('foo', 10);
4
5 try {
6 $lock->block(5);
7
8 // Lock acquired after waiting maximum of 5
seconds...
9 } catch (LockTimeoutException $e) {
10 // Unable to acquire lock...
11 } finally {
12 optional($lock)->release();
13 }
14
15 Cache::lock('foo', 10)->block(5, function () {
16 // Lock acquired after waiting maximum of 5
seconds...
17 });
If you would like to release a lock without respecting its current owner,
you may use the forceRelease method:
1 Cache::lock('foo')->forceRelease();
1 $value = cache('key');
{tip} When testing call to the global cache function, you may use
the Cache::shouldReceive method just as if you were testing a
facade.
Cache Tags
{note} Cache tags are not supported when using the file or
database cache drivers. Furthermore, when using multiple tags
with caches that are stored "forever", performance will be best
with a driver such as memcached , which automatically purges stale
records.
1 Cache::tags(['people', 'authors'])->flush();
1 Cache::tags('authors')->flush();
1 <?php
2
3 namespace App\Extensions;
4
5 use Illuminate\Contracts\Cache\Store;
6
7 class MongoStore implements Store
8 {
9 public function get($key) {}
10 public function many(array $keys) {}
11 public function put($key, $value, $seconds) {}
12 public function putMany(array $values, $seconds)
{}
13 public function increment($key, $value = 1) {}
14 public function decrement($key, $value = 1) {}
15 public function forever($key, $value) {}
16 public function forget($key) {}
17 public function flush() {}
18 public function getPrefix() {}
19 }
1 <?php
2
3 namespace App\Providers;
4
5 use App\Extensions\MongoStore;
6 use Illuminate\Support\Facades\Cache;
7 use Illuminate\Support\ServiceProvider;
8
9 class CacheServiceProvider extends ServiceProvider
10 {
11 /**
12 * Register any application services.
13 *
14 * @return void
15 */
16 public function register()
17 {
18 //
19 }
20
21 /**
22 * Bootstrap any application services.
23 *
24 * @return void
25 */
26 public function boot()
27 {
28 Cache::extend('mongo', function ($app) {
29 return Cache::repository(new MongoStore);
30 });
31 }
32 }
The first argument passed to the extend method is the name of the
driver. This will correspond to your driver option in the
config/cache.php configuration file. The second argument is a
Closure that should return an Illuminate\Cache\Repository
instance. The Closure will be passed an $app instance, which is an
instance of the service container.
1 /**
2 * The event listener mappings for the application.
3 *
4 * @var array
5 */
6 protected $listen = [
7 'Illuminate\Cache\Events\CacheHit' => [
8 'App\Listeners\LogCacheHit',
9 ],
10
11 'Illuminate\Cache\Events\CacheMissed' => [
12 'App\Listeners\LogCacheMissed',
13 ],
14
15 'Illuminate\Cache\Events\KeyForgotten' => [
16 'App\Listeners\LogKeyForgotten',
17 ],
18
19 'Illuminate\Cache\Events\KeyWritten' => [
20 'App\Listeners\LogKeyWritten',
21 ],
22 ];