Laravel basic tutorial-cache

Source: Internet
Author: User
Tags laravel tutorial
Basic laravel tutorial-Cache configuration

Laravel provides unified APIs for multiple cache systems. Cached configuration files are stored in config/cache. php. In this file, you can specify the cache driver used by the entire application by default. Laravel supports mainstream cache systems such as Memcached and Redis.

The cached configuration file also contains some additional configuration options. these options are included in the file with document annotations. you should ensure that you have read these option annotations. By default, the Laravel configuration uses the file cache driver, which stores serialized cache objects in the file system. For large applications, we recommend that you use memory-level caches, such as Memcached or APC. You can even configure multiple cache configurations in laravel to the same driver.

Cache prerequisites

Database

When using the database cache driver, you need to create a table to include these cache items. You can create a table file according to the Schema definition below:

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

You can also use the php artisan cache: table Artisan command to generate a correct cache table structure for migration.

Memcached

To use Memcached cache, you must install Memcached PECL package.

The default configuration is based on Memcached: addServer using TCP/IP:

'memcached' => [  [    'host' => '127.0.0.1',    'port' => 11211,    'weight' => 100  ]],

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

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

Redis

Before using Redis Cache, you must first install predis/predis through Composer. For more information about Redis configuration, refer to Laravel documentation page.

Cache usage to obtain cache instances

The Illuminate \ Contracts \ Cache \ Factory and Illuminate \ Contracts \ Cache \ Repository Contracts provide access to the Laravel Cache service. The Factory contract provides the definition of all cache drivers in the application. The Repository contract is usually implemented 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 Laravel underlying Cache contracts.

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

    

Access multiple types of cache storage

You can access multiple types of Cache storage through the Cache fake store method. The key passed to the store method should match one of the stores configuration items in your cache configuration file:

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

You can get the value of related items from the Cache by using the get method of the Cache mask. If this item does not exist in the cache, null is returned. If you need to, you can also pass the second parameter to the get method. the value passed by this parameter will be returned if the cached item 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 is used as the default value. The method of passing the closure allows you to get the default value from the database or other external services by delay:

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

Check whether the item exists

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

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

Values in increment/decrease items

You can use the increment and decrement methods to adjust the integer value in the cache project. Both methods can accept an array as the second parameter to adjust the corresponding value:

Cache::increment('key');Cache::increment('key', $amount);Cache::decrement('key');Cache::decrement('key', $amount);

Retrieve or update items in the cache

Sometimes, you may want to retrieve a project from the cache, but when the item does not exist, you also want to store a default value to the item. For example, you want to retrieve a user from the cache. But it does not exist, so you need to get it 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 this item is not retrieved in the cache, the closure passed to the remeber method will be executed and the execution result will be replaced in the cache.

You can also merge the remember and forever methods:

$value = Cache::rememberForever('users', function () {  return DB::table('users')->get(); });

Search and delete

If you need to retrieve a project and delete it from the cache while retrieving it, you can use the pull method. Like the get method, if this item is not retrieved, null is returned:

$value = Cache::pull('key');
Store project to cache

You can use the put method of the Cache mask to store the project to the Cache. When you store an item in the cache, you need to specify the minute value for the item to be cached:

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

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

$expiresAt = Carbon::now()->addMinutes(10);Cache::put('key', 'value', $expiresAt);

The add method is added to the cache only when the corresponding item does not exist in the cache. This method returns true after the project is added to the cache. Otherwise, false is returned:

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

The forever method can be used to permanently add a project to the cache. This value can be removed only when the forget method is used manually:

Cache::forever('key', 'value');
Remove a project from the cache

You can use the forget method of the Cache mask to remove an item from the Cache:

Cache::forget('key');

You can use the flush method to erase all the caches:

Cache::flush();

The erased cache does not perform intelligent erasure based on the prefix. it removes all the caches. Therefore, if your application shares the cache with other applications, you should use this method with caution.

Cache tag

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 clear expired records, such as memcached.

Store the marked items to the cache

Cache tags allow you to associate related items. It also allows you to clear cache items for all given labels at a time. You can access the marked cache items through an ordered tag array. For example, let's access the marked project 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 limited to only using the put method. You can use any cache storage method in the tag.

Access marked cache items

To access the marked cache items, you need to pass the corresponding sorted list to the tags method:

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

You can erase all assigned tags or all items in the tag list at a time. For example, you can use the flush method to delete all the people and authors labels and all the cache items in the sequential tags. So 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 preceding statement. it will only delete the authors tag project from the cache, so Anne will be deleted, while John will be retained:

Cache::tags('authors')->flush();
Add a custom cache driver

To inherit the laravel cache from the custom cache driver. We need to use the Cache fake extend method, which is used to bind custom Cache to the underlying management. This is usually done in the service provider.

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

     

The first parameter passed to the extend method should be the driver name. This name should be consistent with the driver option in your config/cache. php configuration file. The second parameter is a closure, which should return an implementation of Illuminate \ Cache \ Repository. A $ app instance will be passed in the closure. This instance is the service container instance in laravel.

Cache: Call the extend method should be completed in the boot method of App \ Providers \ AppServiceProvider. Or you can create your own service provider to store this extension. But do not forget to register in the config/app. php file.

To create our own Cache driver, we first need to implement the Illuminate \ Constracts \ Cache \ Store contract interface. Therefore, our MongoDB cache implementation should look like this:

      

We only need to use MongoDB connection to implement these methods. Once our implementation is complete, we can complete registration of our own cache driver:

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

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

If you are wondering where the custom cache file should be stored, you can consider releasing it to Packagist! Alternatively, you can create an Extensions namespace in the app directory. In fact, you should keep in mind that laravel does not rigidly limit your directory structure. you should be able to freely manage your application directory structure according to your habits.

Event

If you want to execute additional code when any cache is operated, you may need to listen to the cache trigger events. Normally you should store these event listeners to your EventServiceProvider:

/** * 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',  ], ];

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.