cache
to configure
Larave provides a unified API for different cache systems. Cache configuration in config/cache.php
。 In this file, you can specify which cache driver is used by default in the application. Larravel supports mainstream cache backend such as Memcached and Redis Etc.
The cache configuration file also contains other documented options. Be sure to read these options carefully. By default, Larave is configured to use file caching( file
Driver), which stores serialized data and cached objects to the file system. For large applications, it is recommended to use memory cache such as Memcached or APC. You can even configure multiple cache configurations for the same driver.
Drive preparatory knowledge
data base
use database
When cache driven, you need to set a table to store cache entries. The following is the table's Schema
Statement:
Schema::create('cache', function($table) { $table->string('key')->unique(); $table->text('value'); $table->integer('expiration'); });
Note: You can also use Artisan commands php artisan cache:table
Generate migration through corresponding schema.
Memcached
To use Memcached cache, you need to install Memcached PECL Package , that is, PHP Memcached extension. You can use the configuration file config/cache.php
List all Memcached servers in:
'memcached' => [ [ 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100 ], ],
You can also set host
The option is UNIX socket path. If you do this, port
The option should be set to zero
:
'memcached' => [ [ 'host' => '/var/run/memcached/memcached.sock', 'port' => 0, 'weight' => 100 ], ],
Redis
Before using Larave's Redis cache, you need to install it through Composer predis/predis
Package (~1.0).
To learn more about Redis configuration, check Larave's Redis Document 。
Cache Usage
Get cache instance
Illuminate\Contracts\Cache\Factory
and Illuminate\Contracts\Cache\Repository
contract Provides a method to access the Laravel cache service. Factory
The contract provides all cache driven methods for accessing application definitions. Repository
Contracts are usually applied cache
An implementation of the default cache driver specified in the configuration file.
However, you can also use Cache
Facade, which is also the way we use in the whole document, Cache
The facade provides a simple and convenient way to access the underlying Laravel cache contract implementation:
<? php namespace App\Http\Controllers; use Illuminate\Support\Facades\Cache; class UserController extends Controller { /** *Displays a list of all users of the application * * @return Response */ public function index() { $value = Cache::get('key'); // } }
Access multiple cache stores
use Cache
Facade, you can use store
Method to access different cache memory, pass in store
The key of the method is cache
In configuration file stores
The corresponding memory listed in the configuration array:
$value = Cache::store('file')->get('foo'); Cache::store('redis')->put('bar', 'baz', 10);
Get data from cache
Cache
Facade get
Method is used to get the cache item from the cache. If the cache item does not exist, return null
。 If necessary, you can pass the second parameter to get
Method specifies the custom default value returned when the cache item does not exist:
$value = Cache::get('key'); $value = Cache::get('key', 'default');
You can even pass a closure as the default value. If the cache item does not exist, the result of the closure will be returned. Passing closures allow you to obtain default values from databases or other external services:
$value = Cache::get('key', function() { return DB::table(...)-> get(); });
Check whether the cache item exists
has
Method is used to determine whether a cache item exists. If the value is null
or false
This method will return false
:
if (Cache::has('key')) { // }
Value increase/decrease
increment
and decrement
Method can be used to adjust integer values in the cache. Both methods can receive the second parameter to indicate the number of increases and decreases in cache entry values:
Cache::increment('key'); Cache::increment('key', $amount); Cache::decrement('key'); Cache::decrement('key', $amount);
Get&Store
Sometimes you may want to get the cache item, but if the requested cache item does not exist, store a default value for it. For example, you may want to get all users from the cache, or if they do not exist, get them from the database and add them to the cache. You can use Cache::remember
Method implementation:
$value = Cache::remember('users', $minutes, function() { return DB::table('users')->get(); });
If the cache item does not exist, pass it to remember
The closure of the method is executed and the result is stored in the cache.
You can also use rememberForever
Method to obtain data from the cache or store it permanently:
$value = Cache::rememberForever('users', function() { return DB::table('users')->get(); });
Get&Delete
If you need to get the cache item from the cache and delete it, you can use pull
Methods, and get
The method is the same. If the cache item does not exist, it returns null
:
$value = Cache::pull('key');
Store data in cache
You can use Cache
On the facade put
Method stores data in the cache. When you store data in the cache, you need to specify the time (minutes) for the data to be cached:
Cache::put('key', 'value', $minutes);
In addition to passing the cache item expiration time, you can also pass a PHP representing the cache item effective time Datetime
example:
$expiresAt = Carbon::now()->addMinutes(10); Cache::put('key', 'value', $expiresAt);
Store data when cache does not exist
add
Method will only add data to the cache if the cache item does not exist. If the data is successfully added to the cache, it will return true
, otherwise, return false
:
Cache::add('key', 'value', $minutes);
Permanently store data
forever
Method is used to persist the stored data to the cache. These values must be forget
Method to manually remove from the cache:
Cache::forever('key', 'value');
Note: If you use the Memcached driver, the permanently stored data will be removed when the cache data reaches the upper limit.
Remove data from cache
You can use Cache
On the facade forget
Method to remove cache item data from the cache:
Cache::forget('key');
You can also use flush
Method to clear all caches:
Cache::flush();
Note: Clearing the cache does not matter what the cache key prefix is, but removes all data from the cache system. Therefore, when using this method, you need to pay special attention if other applications share caches with this application.
Cache Helper
In addition to using Cache
Facade or Cache contract , you can also use the global cache
Function to get and store data through cache. When the cache
When the function is called, it will return the cache value (value) corresponding to the given key:
$value = cache('key');
If you provide an array of key value pairs and an expiration time for the function, the cache value will be stored (stored) within the specified validity period:
cache(['key' => 'value'], $minutes); cache(['key' => 'value'], Carbon::now()->addSeconds(10));
Test call cache
Function, you can Test facade Same use Cache::shouldReceive
method.
Cache Label
Note: Cache tags are not currently supported file
or database
Cache driven. In addition, when the cache using multiple tags is set to permanent storage memcached
The drive cache has the best performance, because Memcached will automatically clear stale records.
Store tagged cache items
Cache tags allow you to tag related cache items with the same tag for subsequent clearing of these cache values. The tagged cache can be accessed by passing a sorted tag array. For example, we can set labels when adding caches in the following ways:
Cache::tags(['people', 'artists'])->put('John', $john, $minutes); Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);
Access tagged cache entries
To get the tagged cache item, pass the same ordered tag array to tags
Method and then use the key you want to obtain to call get
method:
$john = Cache::tags(['people', 'artists'])->get('John'); $anne = Cache::tags(['people', 'authors'])->get('Anne');
Remove tagged data items
You can clear all cache items marked with the same tag/tag list at the same time. For example, the following statement will remove all cache items marked with the same tag people
or authors
All caches for tags:
Cache::tags(['people', 'authors'])->flush();
In this way, the Anne
and John
Cache entries are removed from the cache.
On the contrary, the following statement only removes the marked authors
Tag, so only Anne
Will be removed and John
can't:
Cache::tags('authors')->flush();
Add a custom cache driver
Write Driver
To create a custom cache driver, first implement the Illuminate\Contracts\Cache\Store
contract Therefore, our MongoDB cache implementation looks like this:
<? php namespace App\Extensions; use Illuminate\Contracts\Cache\Store; class MongoStore implements Store { public function get($key) {} public function many(array $keys); public function put($key, $value, $minutes) {} public function putMany(array $values, $minutes); public function increment($key, $value = 1) {} public function decrement($key, $value = 1) {} public function forever($key, $value) {} public function forget($key) {} public function flush() {} public function getPrefix() {} }
We only need to use a MongoDB connection to implement each of these methods. If you want to see an example of how to implement each method, you can refer to the underlying source code of Laravel Illuminate\Cache\MemcachedStore
After the implementation, we can complete the custom driver registration:
Cache::extend('mongo', function($app) { return Cache::repository(new MongoStore); });
Note: If you are worried about where to put the custom cache driver code, you can app
Create a Extensions
Namespace. However, remember that Larravel does not have a strict application directory structure. You can freely organize the directory structure based on your needs.
Registration Driver
To register a custom cache driver through Larave, you can use the Cache
On the facade extend
method. yes Cache::extend
The call of can be made in the App\Providers\AppServiceProvider
Provided boot
Method, or you can create your own service provider to store the extension -- just don't forget to set it in the configuration file config/app.php
Register service provider to providers
Array:
<? php namespace App\Providers; use App\Extensions\MongoStore; use Illuminate\Support\Facades\Cache; use Illuminate\Support\ServiceProvider; class CacheServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void * @translator laravelacademy.org */ public function boot() { Cache::extend('mongo', function($app) { return Cache::repository(new MongoStore); }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }
Pass to extend
The first parameter of the method is the driver name. This value corresponds to the configuration file config/cache.php
In driver
Option. The second parameter is to return Illuminate\Cache\Repository
Closure of the instance. A $app
Instance, that is Service Container An instance of.
After the extension is registered, simply update the configuration file config/cache.php
Of driver
The option is custom extension name.
Cache Events
To execute code during each cache operation, you can listen to the cache triggered event Usually, you can put the cache processor code into EventServiceProvider
Medium:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Cache\Events\CacheHit' => [ 'App\Listeners\LogCacheHit', ], 'Illuminate\Cache\Events\CacheMissed' => [ 'App\Listeners\LogCacheMissed', ], 'Illuminate\Cache\Events\KeyForgotten' => [ 'App\Listeners\LogKeyForgotten', ], 'Illuminate\Cache\Events\KeyWritten' => [ 'App\Listeners\LogKeyWritten', ], ];