Laravel Basic Tutorial--cache

Source: Internet
Author: User
Tags event listener

Cache

Configuration

The Laravel provides a unified API for multiple cache systems. The cached configuration file is stored in the config/cache.php. You can specify in this file which cache driver the entire app will use by default. Laravel supports current mainstream cache systems such as Memcached and Redis.

The cached configuration file also contains some additional configuration options, which have documentation comments in the file, and you should make sure that you have read these option comments. By default, the Laravel configuration uses the file cache driver, which stores the serialized cache object in the filesystem. For large applications, it is recommended to use a memory-level cache, such as Memcached or APC. You can even configure multiple cache configurations to the same driver in Laravel.

Cache Prerequisites

Database

When using the database cache driver, you need to create a table to contain these cache entries. You can create a table file based on the following Schema definition:

Schema::create (' Cache ', function ($table) {  $table->string (' key ')->unique ();  $table->text (' value ');  $table->integer (' Expiration '); });

You can also generate the correct cache table structure migration by using the PHP artisan cache:table artisan command.

Memcached

The Memcached PECL package needs to be installed using the Memcached cache.

The default configuration is based on memcached::addserver using TCP/IP:

' Memcached ' = [    ' host ' = ' 127.0.0.1 ',    ' port ' = ' 11211 ',    ' weight ' = +  ]],

You can also use the UNIX socket path to set host. If you do this, you need to set the port to 0:

' Memcached ' = [    ' host ' = '/var/run/memcached/memcached.sock ',    ' port ' = 0,    ' weight ' = >  ],

Redis

Before you can use the Redis cache, you need to install Predis/predis through Composer first. For more information on Redis configuration, you can refer to the Laravel documentation page.

Cache usage

Get Cache Instance

The Illuminate\contracts\cache\factory and Illuminate\contracts\cache\repository contracts provide access to the Laravel cache service. The Factory contract provides definitions for all cache drivers in the application. The Repository contract is typically an implementation that is based on the default cache driver used by your cache configuration file.

In fact, you can also use the cache mask, in this document, we use the cache mask for example. The cache mask provides a convenient and concise way to access the implementation of the Laravel underlying cache contract.

For example, let's introduce the Cache mask to the controller:

    

Access to multiple cache storage

You can access a variety of cache stores by using the cache mask's Store method. The key passed to the store method should match one of the list of stores configuration items in your cache configuration file:

$value = Cache::store (' file ')->get (' foo '); Cache::store (' Redis ')->put (' Bar ', ' Baz ', 10);

Get Cache entry

You can get the value of the related item from the cache by using the Get method of the cache mask. If the item does not exist in the cache, NULL is returned. If you want, you can also pass the second argument to the Get method, and the value passed by this parameter will be returned when the item in the cache does not exist:

$value = Cache::get (' key '); $value = Cache::get (' key ', ' default ');

You can even pass Closure as the default value. If the cached item does not exist, the value returned by Closure will be the default value. Passing closures allows you to defer getting the default values from the database or other external services:

$value = Cache::get (' key ', function () {  return db::table (...) ->get (); });

Check if an item exists

You can use the has method to check if the item exists in the cache:

if (Cache::has (' key ')) {  //}

Increment/Decrement A value in an item

You can use the increment and decrement methods to adjust the integer values in the cached item. Both of these methods can accept an array as the second parameter to adjust the corresponding values:

Cache::increment (' key '); Cache::increment (' key ', $amount); Cache::d ecrement (' key '); Cache::d ecrement (' key ', $amount);

Retrieving or updating items in the cache

Sometimes you might want to retrieve an item from the cache, but when the item does not exist, you also want to store a default value to that item. For example, you want to retrieve a user from the cache. But he doesn't exist, so you need to get him from the database and add it to the cache. You can use the Cache::remember method to do this:

$value = Cache::remember (' Users ', $minutes, function () {  return db::table (' users ')->get ();});

If the item is not retrieved in the cache, the closure that is passed into the Remeber method is executed and its execution results are replaced in the cache.

You can also merge remember and Forever methods:

$value = Cache::rememberforever (' Users ', function () {  return db::table (' users ')->get ();});

Retrieving and deleting

If you need to retrieve an item and delete the item from the cache while retrieving it, you can use the Pull method. Just like the Get method, if the item is not retrieved, NULL will be returned:

$value = Cache::p ull (' key ');

Store items to cache

You can use the Put method of the cache mask to store items in the cache. When you store an item in the cache, you need to specify a minute value that the item needs to be cached:

Cache::p ut (' key ', ' value ', $minutes);

In addition to passing a number as a value for the minute that the cache expires, you can also set the cache expiration time by passing a PHP DateTime instance:

$expiresAt = Carbon::now ()->addminutes (10); Cache::p ut (' key ', ' value ', $expiresAt);

The Add method will only be added to the cache if the corresponding item does not exist in the cache. This method returns true after the item has been added to the cache. Otherwise, false is returned:

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

The Forever method can be used to permanently add items to the cache. This value can only be removed by using the Forget method manually:

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

Removing items from the cache

You can use the Forget method of the cache mask to remove an item from the buffer:

Cache::forget (' key ');

You can use the Flush method to erase all caches:

Cache::flush ();

Erasing a cache does not have a smart erase based on the prefix, it removes all caches. So if your app and other apps share the cache, you should use this method with caution.

Cache tags

Note: Cache tags do not support file or database cache drivers. In addition, for drivers that mark multiple tags as permanent storage, the best performance is to provide drivers that automatically purge outdated records, such as memcached.

Store tagged items to cache

The cache tag allows you to associate related items with tags. and allows you to clear all cache entries for a given label at once. You can access tagged cache items through an ordered array of tags. For example, let's access the tagged item and use the Put method to set the cache value:

Cache::tags ([' People ', ' artists '])->put (' John ', $john, $minutes); Cache::tags ([' People ', ' authors '])->put (' Anne ', $anne, $minutes);

In fact, you are not restricted to using the Put method only. You can use any of the cache storage methods in the tag.

Access to tagged cache entries

In order to access the tagged cache entries, you need to pass the appropriate ordered list to the tags method:

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

You can erase an assigned tag or tag all items in a list at once. For example, you can use the Flush method to delete all of the people and authors tags and all the cache entries in the sequence tags that make up both. Therefore, both Anne and John are removed from the cache:

Cache::tags ([' People ', ' authors '])->flush ();

The following statement will be used as a comparison of the above statements, and only the items of the authors tag will be deleted from the cache, so Anne is removed and John is reserved:

Cache::tags (' authors ')->flush ();

Add a custom cache driver

In order to inherit the cache of Laravel in a custom cache drive. We need to use the Extend method of the cache mask, which is used to bind custom caches to the underlying management. Typically, these are done in the service provider.

For example, register a new cache driver and name it ' MONGO ':

     

The first parameter that is passed to the Extend method should be the name of the driver. This name should be the same as the driver option in your config/cache.php configuration file. The second parameter is a closure, and the closure should return an illuminate\cache\repository implementation. A $app instance will be passed in the closure, which is an instance of the service container in Laravel.

The invocation of the Cache::extend method should be done in the App\providers\appserviceprovider boot method. Or you can create your own service provider to store this extension. But don't forget to register in the config/app.php file.

In order to create our own cache driver, we first need to implement the interface of the Illuminate\constracts\cache\store contract. So, our MongoDB cache implementation should look like this:

      

We just need to use MongoDB connections to implement these methods. Once our implementation is complete, we can complete our own cache-driven registration:

Cache::extend (' MONGO ', function ($app) {  return cache::repository (new Mongostore);});

Then, in the config/cache.php configuration file, update the name of the driver to driver for your extension.

If you're wondering where you should store your custom cache files, you can consider publishing them to packagist! Alternatively, you can create a Extensions namespace in the app directory. In fact, you should keep in mind that Laravel does not rigidly restrict your directory structure, you should be able to freely manage your application directory structure according to your own habits.

Event

If you want to execute additional code when any cache is being manipulated, you may need to listen for cached triggering events. Usually you should store these event listeners into your eventserviceprovider:

/** * The event listener mappings for the application. * * @var Array */protected $listen = [  ' illuminate\cache\events\cachehit ' = [    ' App\listeners\logcachehit ', c2/>],  ' illuminate\cache\events\cachemissed ' = [    ' app\listeners\logcachemissed ',  ],  ' Illuminate\cache\events\keyforgotten ' = [    ' App\listeners\logkeyforgotten ',  ],  ' illuminate\cache\ Events\keywritten ' = [    ' App\listeners\logkeywritten ',  ],];
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.