This is a review material for the Laravel certification exam with Laravel 9 version, which refreshes the purpose of reviewing and preserving my “serious” study days. There is no better way to learn than by sharing knowledge with others, right?
This time I work on caching in Laravel.
I. About cache in Laravel
Laravel is a very powerful framework for making the web that everyone has to recognize, so “it” provides programmers with a lot of great tools and features, including caches. So what is cache?
Cache is a temporary memory used to store frequently accessed data or resources during the operation of a software application. Using a cache helps to reduce the time it takes to access data from the primary storage system (such as a database or memory) by keeping copies of that data in temporary memory. When the application needs to access data, it will access the previous cache to get the data faster.
Cache is widely used in web applications and mobile applications to improve the speed and performance of the application. The data stored in the cache can be web pages, image resources, text documents, database query results, or any other type of data that needs to be accessed frequently. The use of cache is one of the strategies to improve the performance of software applications, especially in large and complex systems.
II. What items should be understood when learning Laravel cache?
1. Drivers/Configuration
In caching, drivers and configuration play an important role to manage cache and optimize system performance. Here are some insights into these two concepts:
1. Drivers:
- Drivers are components of the caching layer (temporary storage layer) that connect to data storage systems such as Redis, Memcached, or other data storage systems.
- When implementing caching, developers can choose the right driver for their system to increase the performance and reliability of the caching layer.
- Some common drivers in the caching layer include: Memcached driver , Redis driver , Database cache driver , DynamoDB cache driver and File driver .
2. Configuration:
- Configuration defines how the caching layer works.
- Through configurations, developers can customize parameters to increase performance and optimize temporary data storage.
- Configuration parameters can include cache size, cache entries lifetime, cache clearing policies, temporary memory locking and release mechanisms, and much more.
3. Introducing 4 types of cache drivers that laravel provides
- File caching : Laravel supports file caching through the “file” driver. When using this driver, cache items will be stored in files on disk, and you can configure the cache storage directory.To use file caching, you need to first configure the cache driver in the
config/cache.php
file by setting the value ‘file’ for the key ‘default’:'default' => 'file',
- Memcached : A distributed caching system and widely used to speed up data access in web applications. Laravel provides support for Memcached through the
memcached
driver.To use Memcached in Laravel, you need to install Memcached on your server or use services that provide Memcached like Amazon ElastiCache or Google Cloud Memorystore.Once you’ve installed Memcached, you can configure the cache driver in the
config/cache.php
file by setting thememcached
value for thedefault
key and configuring the Memcached server:
123456789101112131415161718192021 'default' => 'memcached','memcached' => ['driver' => 'memcached','persistent_id' => env('MEMCACHED_PERSISTENT_ID'),'sasl' => [env('MEMCACHED_USERNAME'),env('MEMCACHED_PASSWORD'),],'options' => [// Định cấu hình các tùy chọn MemcachedMemcached::OPT_CONNECT_TIMEOUT => 2000,],'servers' => [['host' => env('MEMCACHED_HOST', '127.0.0.1'),'port' => env('MEMCACHED_PORT', 11211),'weight' => 100,],],],
- Redis : A distributed database and cache storage system widely used to speed up data access in web applications. Laravel provides support for Redis through the “redis” driver.To use Redis in Laravel, you need to install Redis on your server or use Redis provisioning services like Amazon ElastiCache or Google Cloud Memorystore
Once you have installed Redis, you can configure the cache driver in the config/cache.php file by setting the ‘redis’ value for the ‘default’ key and configuring the Redis server:
12345678910111213141516 'default' => 'redis','redis' => ['client' => 'phpredis','options' => ['cluster' => 'redis','prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),],'default' => ['url' => env('REDIS_URL'),'host' => env('REDIS_HOST', '127.0.0.1'),'password' => env('REDIS_PASSWORD', null),'port' => env('REDIS_PORT', 6379),'database' => env('REDIS_DB', 0),],],
- Database caching : A database-based caching mechanism in which copies of query requests are stored in the database for reuse for the same query requests. Laravel provides support for database caching through the “database” driver.To use database caching in Laravel, you need to create a table to store cached copies. This table should have the fields: ”
key
“, ”value
“, ”expiration
” and ”tags
” (optional). You can create this table with the migration statement in Laravel or create it manually.After you have created the cache table, you need to configure the cache driver in the config/cache.php file by setting the
database
value for thedefault
key and configuring the database connection:
12345678910 'default' => 'database','connections' => ['database' => ['driver' => 'database','table' => 'cache','connection' => null,],],
- More about DynamoDB cache driverDynamoDB is an Amazon Web Services (AWS) NoSQL database service that is used to store structured or unstructured data. DynamoDB is designed to provide high availability and scalability, so it is a popular choice for storing data in the cloud.
In Laravel, you can use DynamoDB cache driver to store cache on DynamoDB. To use this driver, you need to install the AWS SDK for PHP first. Then we need to configure the driver in Laravel’s
config/cache.php
file as follows:
12345678 'dynamo' => ['driver' => 'dynamodb','key' => 'your-aws-key','secret' => 'your-aws-secret','region' => 'your-aws-region','table' => 'your-dynamodb-table',],
12345678 use IlluminateSupportFacadesCache;// Lưu trữ một giá trị vào cacheCache::store('dynamo')->put('key', 'value', $expiration);// Lấy giá trị từ cache$value = Cache::store('dynamo')->get('key');
4. Which caching method is the best
No one caching method is best for all cases, because each caching method has its own advantages and limitations, and depending on the needs of the application, the appropriate caching method will be different. together.
There are several factors to consider when choosing a caching method, including:
- Frequency of data access: If data is accessed frequently, using in-memory caching like Redis or Memcached may be best.
- Data size: If the data size is very large, using file caching or database caching may be a better choice.
- Number of concurrent queries: If multiple users access at the same time, memory caching may not be appropriate, and database caching may be better.
- Data Consistency: If data consistency is very important, using memory caching or Redis methods may be best, as they can support transactions and locks to ensure data consistency.
- Scalability: If your application needs to scale to multiple servers, using Redis or Memcached is best, as they support distributed cache across multiple servers.
=> So, in order to choose the most suitable caching method for your application, you need to carefully consider the above factors and learn about different caching methods to be able to make the right decision.
Some typical examples of different types of cache
- Cache file : A news website can use a cache file to store the content of articles and homepages. When users visit the homepage or article, the content will be stored in the cache file to reduce page load time and speed up access for users.
- Cache Redis : An online game service that may use the Redis cache to store information about players, scores, and game configurations. Redis provides in-memory data storage to reduce the time it takes to retrieve data from the database.
- Cache Memcached : An e-commerce application can use the Memcached cache to store information about the user’s products and shopping cart. When users add products to the cart, the information will be stored in Memcached cache to reduce page reload time and increase the shopping experience for users.
- Cache database : A project management application can use a cache database to store information about project status, next steps, and project participants. Cache database helps to reduce database access time and increase application speed.
- Session Cache : A login application can use session-based cache to store user credentials. When a user logs in, the credentials are stored in session-based cache to reduce database retrieval time and increase application speed.
2. Store Items
In Laravel, to cache an item, we can use the methods of the Cache facade, such as put
, add
, forever
, or remember
.
The general syntax for these methods is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | use IlluminateSupportFacadesCache; // Lưu trữ một item vào cache trong một khoảng thời gian nhất định Cache::put('key', 'value', $expiration); // Lưu trữ một item vào cache trong một khoảng thời gian nhất định nếu chưa tồn tại Cache::add('key', 'value', $expiration); // Lưu trữ một item vào cache với thời gian sống vô hạn Cache::forever('key', 'value'); // Lấy một item từ cache, nếu không tồn tại thì tạo mới và lưu trữ trong cache $value = Cache::remember('key', $expiration, function () { return 'value'; }); |
Where, $expiration is the lifetime of the item in the cache, in seconds. If $expiration is not provided, the item will be cached with the default lifetime configured in the config/cache.php
file.
When storing an item in the cache, Laravel uses the currently configured cache driver to cache the item. Cache drivers can be file, database, redis, or other custom cache drivers.
When we need to retrieve an item from the cache, we simply use the get method of the Cache facade:
1 2 | $value = Cache::get('key'); |
If the item does not exist in the cache, the get method will return null
.
To remove an item from the cache, we can use the forget
method:
1 2 | Cache::forget('key'); |
If we need to clear all items in the cache, we can use the flush method:
1 2 | Cache::flush(); |
3. Retrieving Items
To retrieve an item from the Laravel cache, we may use the get method of the Cache facade:
1 2 | $value = Cache::get('key'); |
In which, key
is the key of the item to be retrieved.
If the item exists in the cache, get will return the value of the item. Otherwise, get will return null
. Alternatively, we can use the get
method to get the default value if the item doesn’t exist:
1 2 | $value = Cache::get('key', 'default'); |
Where default
is the default value returned if the item does not exist in the cache.
If we want to check if the item exists in the cache, we can use the has
method:
1 2 3 4 5 6 | if (Cache::has('key')) { // Item exists in cache } else { // Item does not exist in cache } |
If we need to retrieve and remove an item from the cache immediately, we can use the pull
method:
1 2 | $value = Cache::pull('key'); |
In it, pull
will get the value of the item and remove the item from the cache. If the item does not exist in the cache, pull
will return null
.
4. Cache Tags
Cache tags is a powerful feature of Laravel Cache that allows you to assign tags to items in the cache, and allows you to retrieve and delete all items with the same tag easily.
To assign tags to an item in the cache, we may use the tags
method on the Cache facade:
1 2 | Cache::tags(['tag1', 'tag2'])->put('key', 'value', $minutes); |
Where, ['tag1', 'tag2']
is the list of tags assigned to the item.
To retrieve all items tagged with a tag, we may use the tags method on the Cache facade:
1 2 | $items = Cache::tags('tag1')->get('key'); |
Where, tag1
is the tag used to get the items.
We may also remove all items tagged with a tag using the tags
method on the Cache facade:
1 2 | Cache::tags('tag1')->flush(); |
In which, tag1
is the tag used to delete items.
Note that tags can be used to assign a number of items in the cache, and these items can have different tags. However, it should be noted that when deleting items by tag, only items that are tagged with that tag will be deleted. Other items in the cache are preserved.
Practical example of assigning tags to cache
Suppose we have a sales web application in which we store information about products and prices in a database. When the user visits the product page, we need to get the product and price information from the database. However, querying the database can take a long time, slowing down the responsiveness of the website.
To solve this problem, we can use cache to store information about products and prices, and use cache tags to manage items in the cache. In this case, we can attach the tags product_{id}
and price_{id}
to the items in the cache, with id
being the product code.
When the user visits the product page, we first check if the product and price information is in the cache, if so, return that information from the cache. Otherwise, we query the database for product and price information, and cache that information with the corresponding tags.
When information about a product or the price of a product is updated in the database, we need to delete the items in the cache with the corresponding tag
to ensure that the information retrieved from the cache is always the latest information.
5. Creating Custom Drivers
When you use a special type of caching system that is not supported by default Laravel, or when you want to customize or improve your cache in your own way, you may need to create a Custom Driver.
Also, in some cases, you may want to create a Custom Driver to use different caching mechanisms for different parts of your application, depending on your requirements and type of storage.
In Laravel, you can create your own custom cache drivers by implementing the IlluminateContractsCacheStore
interface. This allows you to use other databases or storage technologies to store your cache.
- To create a custom cache driver, you need to do the following:
- Create a new class that implements
IlluminateContractsCacheStore
. This will be your cache driver class. - Implement
get
,put
,increment
,decrement
,forever
,forget
methods of interfaceIlluminateContractsCacheStore
.
Register your driver in config/cache.php
and specify the driver name, along with the necessary configurations to connect to your storage technology.
Here’s an example of how to create a custom cache driver that uses the Redis caching mechanism:
- Create a
RedisCacheStore
class that implementsIlluminateContractsCacheStore
interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | use IlluminateContractsCacheStore; use IlluminateSupportFacadesRedis; class RedisCacheStore implements Store { public function get($key) { $value = Redis::get($key); return $value ? unserialize($value) : null; } public function put($key, $value, $seconds) { $value = serialize($value); Redis::setex($key, $seconds, $value); } public function increment($key, $value = 1) { return Redis::incrby($key, $value); } public function decrement($key, $value = 1) { return Redis::decrby($key, $value); } public function forever($key, $value) { $value = serialize($value); Redis::set($key, $value); } public function forget($key) { Redis::del($key); } } |
- Register the
RedisCacheStore
driver inconfig/cache.php
:
1 2 3 4 5 | 'redis_custom' => [ 'driver' => 'custom_redis', 'connection' => 'cache', ], |
- Specify the connection configuration in
config/database.php
:
1 2 3 4 5 6 7 8 | 'cache' => [ 'url' => env('REDIS_URL'), 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_CACHE_DB', '1'), ], |
After completing the above steps, you can use the redis_custom
driver to store cache in Redis.
References: https://laravel.com/docs/9.x/cache