[Laravel 5.2 Document] service--cache

Source: Internet
Author: User
Tags php memcached

1. Configuration

Laravel provides a unified API for different cache systems. The cache configuration is located in config/cache.php. In this file you can specify which cache driver is used by default in your app. Laravel currently supports mainstream cache backend such as memcached and Redis.

The cache profile also contains additional documented options to ensure that these options are read carefully. By default, Laravel is configured to use the file cache, which stores the serialized data and cached objects to the file system. For large applications, it is recommended that you use memory caches such as memcached or APC, and you can even configure multiple cache configurations for the same driver.

1.1 Cache Readiness Knowledge

Database

When using the database cache driver, you need to set up a table that contains cache cache entries. Here is the schema declaration for the table:

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

Memcached

Using the Memcached cache requires the installation of the Memcached PECL package, which is the PHP Memcached extension.

Memcached::addserver default configuration uses the TCP/IP protocol:

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

You can also set the host option to a UNIX socket path, and if you do, the port option should be reset to 0:

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

Redis

Before using the Laravel Redis cache, you need to install the Predis/predis package (~1.0) through Composer.

To learn more about Redis configuration, check out the Redis documentation for Larave.

2. Cache usage

2.1 Getting a cache instance

The Illuminate\contracts\cache\factory and illuminate\contracts\cache\repository contracts provide a way to access the Laravel cache service. The factory contract provides all the methods to access the cache driver defined by the application. The repository contract is typically an implementation of the default cache driver specified in the cache configuration file in the app.

However, you can also use the cache façade, which is the way we use it throughout the document, and the cache façade provides a simple and convenient way to access the underlying Laravel cache contract implementation.

For example, let's import the cache façade in the controller:

     

accessing multiple cache Stores

Using the cache façade, you can access different cache memory using the store method, and the key to the store method is the corresponding memory listed in the stores configuration array in the cache configuration file:

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

2.2 Fetching data from the cache

The Get method of the cache façade is used to get the cache entry from the cache and returns null if the cache entry does not exist. If necessary, you can pass the second argument to the Get method to specify a custom default value that is returned when the cache entry does not exist:

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

You can even pass a closure as the default value, and if the cache entry does not exist, the result of the closure will be returned. Transitive closures allow you to obtain default values from a database or other external service:

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

Check if the cache entry exists

The has method is used to determine whether a cache entry exists:

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

Value Increase/decrease

The increment and decrement methods can be used to adjust integer values in the cache. Both methods can receive the second parameter to indicate the number of cache entry values increasing and decreasing:

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

Get or update

Sometimes you might want to get a cache entry, but store a default value if the requested cache entry does not exist. For example, you might want to get all the users from the cache, or if they don't exist, get them from the database and add them to the cache, which you can do by using the Cache::remember method:

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

If the cache entry does not exist, the closure passed to the Remember method is executed and the result is stored in the cache.

You can also combine remember and forever methods:

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

Get and delete

If you need to get the cache entry from the cache and then delete it, you can use the Pull method, like the Get method, to return NULL if the cache entry does not exist:

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

2.3 Storing cache entries to the cache

You can use the Put method on the cache façade to store the cache entries in the caches. When you store cache entries in the cache, you need to specify how long the data will be cached (in minutes):

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

In addition to passing cache entry expiration times, you can also pass a PHP datetime instance that represents the time that the cache entry is valid:

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

The Add method only adds cache entries to the cache if the cache entry does not exist, and returns true if the cache entry is added to the cache, otherwise false:

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

The Forever method is used to persist storage cache entries to the cache, and these values must be manually removed from the cache through the Forget method:

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

2.4 Removing data from the cache

You can use the Forget method on the cache façade to remove cache entries from caches:

Cache::forget (' key ');

You can also use the Flush method to clear all caches:

Cache::flush ();

By clearing the cache and removing all the data from the cache system, regardless of the cache key prefix, you need to be careful when using this method if other apps have shared caches with the app.

3. Cache tags

Note: Cache tags currently do not support file or database cache drivers, and when caching with multiple tags is set to persistent storage, caching with Memcached drives is best performance because Memcached automatically cleans up stale records.

3.1 Store Tagged cache entries

The cache tag allows you to label the associated cache entry with the same tag to facilitate subsequent cleanup of these cached values, and the tagged cache can be accessed by passing a sorted array of tags. For example, we can set a tag when adding a cache in the following ways:

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

There is no limit to the number of cache entries that you can label.

3.2 Access to tagged cache entries

To get tagged cache entries, pass the same ordered array of tags to the tags method:

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

You can also clear all cache entries that have been hit on the same label/tag list, for example, the following statement removes all caches that were tagged with people or authors:

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

This will remove the Anne and John cache entries set above from the cache.

Instead, the following statement only removes the statement labeled authors, so only Anne will be removed and John will not:

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

4. Add a custom cache driver

To extend the Laravel cache with a custom driver, you can use the Extend method provided by the cache façade, which is used to define the drive resolver to the manager, which is typically done in the service provider.

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

      

The first argument passed to the Extend method is the driver name. This value corresponds to the driver option in configuration file config/cache.php. The second parameter is a closure that returns the Illuminate\cache\repository instance. The closure is passed into a $app instance, which is an instance of the service container.

The call to Cache::extend can be done in the boot method in the default App\providers\appserviceprovider, or you can create your own service provider to hold the extension-just don't forget to configure the file config/ The provider is registered in the app.php.

To create a custom cache driver, you first need to implement the Illuminate\contracts\cache\store contract, so our MongoDB cache implementation looks like this:

       

We only need to use MongoDB connection to implement each method, after completion, we can complete the custom driver registration:

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

After the extension is complete, you only need to update the configuration file config/cache.php The driver option for your extension name.

If you're worried about where to put your custom cache driver code, consider putting it in packgist! Alternatively, you can create a extensions namespace under the app directory. However, remember that Laravel does not have a strict application directory structure, and you can organize the directory structure freely based on your needs.

5. Cache Events

To execute code every time a cache operation is performed, you can listen for cache-triggered events, and in general, you can put these cache processor code in 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.