cache


1. Configuration

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. Larave currently 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, 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.

1.1 Cache preliminary knowledge

data base

use database When cache driven, you need to set a table to contain 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'); });
Memcached

To use Memcached cache, you need to install Memcached PECL Package , that is, PHP Memcached extension.

Memcached::addServer The default configuration uses TCP/IP protocol:

 '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

2. Cache Usage

2.1 Obtaining Cache Instances

Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository The contract provides a way to access the cache service of Laravel. Factory Contracts provide 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 throughout the document, Cache The facade provides a simple and convenient way to access the underlying Laravel cache contract implementation.

For example, let's import in the controller Cache Facade:

 <? php namespace App\Http\Controllers; use Cache; use Illuminate\Routing\Controller; class UserController extends Controller{ /** *Display the list of all users of the app * * @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 in the cache configuration file stores The corresponding memory listed in the configuration array:

 $value = Cache::store('file')->get('foo'); Cache::store('redis')->put('bar', 'baz', 10);

2.2 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, null is returned. 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 (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 or update

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 unite remember and forever method:

 $value = Cache::rememberForever('users', function() { return DB::table('users')->get(); });
Get and 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, null is returned:

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

2.3 Storing Cache Entries to Cache

You can use Cache On the facade put Method stores cache entries in the cache. When you store cache items in the cache, you need to specify the time (minutes) for 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);

add Method will only add a cache item to the cache if the cache item does not exist. If the cache item is added to the cache, it will return true , otherwise, return false

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

forever Method is used to persist cache entries to the cache. These values must be forget Method to manually remove from the cache:

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

2.4 Removing Data from the Cache

You can use Cache On the facade forget Method to remove a cache entry from the cache:

 Cache::forget('key');

You can also use flush Method to clear all caches:

 Cache::flush();

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 should pay special attention if other applications share the cache with this application.

3. 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.

3.1 Storage of 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);

You can label multiple cache items with the same label. There is no limit to the number.

3.2 Access to tagged cache items

To get the tagged cache item, pass the same ordered tag array to tags method:

 $john = Cache::tags(['people', 'artists'])->get('John');$ anne = Cache::tags(['people', 'authors'])->get('Anne');

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();

4. Add a custom cache driver

To extend the Larave cache using a custom driver, you can use the Cache Provided by the facade extend Method, which is used to bind and define the drive parser to the manager. Usually, this can be done in Service Provider Completed in.

For example, to register a new cache driver named "mongo":

 <? php namespace App\Providers; use Cache; use App\Extensions\MongoStore; use Illuminate\Support\ServiceProvider; class CacheServiceProvider extends ServiceProvider{ /** * Perform post-registration booting of services. * * @return void */ 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.

call Cache::extend Can be set in the default App\Providers\AppServiceProvider In 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 the provider in.

To create a custom cache driver, first implement the Illuminate\Contracts\Cache\Store Contract, so our MongoDB The cache implementation looks like this:

 <? php namespace App\Extensions; class MongoStore implements \Illuminate\Contracts\Cache\Store{ public function get($key) {} public function put($key, $value, $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 just need to use MongoDB Connect and implement each method. After the implementation, we can complete the custom driver registration:

 Cache::extend('mongo', function($app) { return Cache::repository(new MongoStore); });

After the extension is completed, only the configuration file needs to be updated config/cache.php Of driver The option is your extended name.

If you are worried about where to put the custom cache driver code, consider putting it in Packlist! Or, 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.

5. Cache Events

To execute code during each cache operation, you can listen to the events triggered by the cache. Usually, you can put these cache processor codes 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', ], ];

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Subscription payment implementation: Laravel Cashier

>>Next: aggregate