Configuration and example of laravel framework cache usage

Source: Internet
Author: User
Tags apc auth join memcached php file redis redis server

Basic Introduction

Assume that your application displays ten of the most popular songs for user voting. Do you really need to access these 10 songs each time a user accesses them? What if you can store 10 minutes of songs or even an hour to greatly speed up your application? Using laravel cache becomes very simple.

Laravel provides five cache driver modes:

• File system
• Database
• Memcached
• APC
• Redis
• Memory (Arrays)

By default, Laravel is configured to use the file system cache driver, which does not need to be configured. the file system driver stores cached items as files in the storage/cache directory. if you are satisfied with this driver, no other configuration is required. use it directly:

Tip: before using the file system cache driver, make sure that your storage/cache directory is writable.


Database

The database cache uses the given simple key value to store the database table. Before using the database, first set the name of the database table in the application/config/cache. Php file:

1. 'Database' => array ('table' => 'laravel _ cache'). Next, create a database table. The table should have three columns:

• Key (varchar)
• Value (text)
• Expiration (integer)
That's it. Once your configuration and table settings are set, start using the cache!


Memcached
Memcached is an open-source distributed memory object cache system that is used by websites such as Wikipedia and Facebook. before using Laravel Memcached driver, you will need to install and configure memcached and PHP memcache extension on your server.

Once Memcached is installed on the server, you must set the driver on the application/config/cache. Php file:

1. 'Driver '=> 'memcached' and then add your memcached server to the servers array.


Redis
Redis is an open-source and advanced key-value repository. it is usually called a data structure server, because the key can contain strings, hashes, lists, sets, and sorted sets.

Before using the Redis cache driver, set the Redis server. Set the driver on the application/config/cache. Php file:

1. 'Driver '=> 'redis'
Cache key value
To avoid conflicts with the names of APC, Redis, or memcached used by other applications, Laravel has prepared a key attribute in advance as the prefix for using these drivers. You can change this value at will:

1. 'Key' => 'laravel'
Memory (In-Memory) cache

The "memory" cache driver does not actually cache any content on the disk. it is only an internal array that maintains the cache data of the current request. this enables unit testing before any caching mechanism is complete. it should not be used as a "real" cache driver.


In fact, in a sense, session is also a cache technology. For more information, see the following analysis.
Laravel's cache supports drivers such as file, database, apc, memcached, redis, and array, here we mainly talk about memcached and redis,

Laravel framework, you will find that it does not support memcache caching, but memcached caching. Why, in fact, memcached cache is an upgraded version of memcache, compared with a lock mechanism, for details, go to Baidu. You can find the memcached cache configuration in the cache. Php file.

In redis, redis configuration items cannot be found in cache. php. So where? In the databases. Php file, laravel configures it as a DB.

For the same session, if your driver chooses redis, his configuration is also selected here.

The following is my configuration code:

$ RedisCache = App: make ('cache'); // Assumes "redis" set as your cache
$ RedisCache-> setConnection ('cache'); // Your redis cache connection
$ RedisCache-> put ('testtcacheindex', 'fbbinvalue', 10000 );

13 .), one of the problems I have to mention here is that we can only use the default configuration item when configuring the redis-driven cache service or session service, rather than specifying the specific configuration item, for example, if I want to configure the server specified by the cache key for my cache and set other sessions, laravel does not support soy sauce (maybe I don't know how to do it yet, if you know this, please kindly advise, thank you). What should we do if we want our cache server to use the service specified by our specified cache index? We can try laravel's IOC, as shown below:

Solution 1:

$ Redis = Redis: connection ('cache ');
$ Redis-> set ('fbbin', 'fbbinvalue ');
Var_dump ($ redis-> get ('fbbin '))

In this example, Caching is used to cache data to relieve the pressure on database queries.

Let's talk less about it. Let's start with my specific needs:
    
I. Implement data caching on the home page. If there is a cache that has not expired, the database will not be checked. This basically simulates the static page effect (of course, it still needs to be processed by php)

2. Implement the function of refreshing the specified cache (only the home page is available here, and the homepage cache is refreshed by a single means. This function is implemented under the admin module.

Specific implementation:
  
1. Check the document and find the module that can help me meet the requirements.

I checked the document and found that a module such as Caching, as its name implies, is a cache. Can it help me? Let's see first:

1. Http://laravel.com/docs/cache/config here is the implementation of laravel's Caching module

2. The document is described as follows:
The Basics Imagine your application displays the ten most popular songs as voted on by your users. Do you really need to look up these ten songs every time someone visits your site? What if you cocould store them for 10 minutes, or even an hour, allowing you to dramatically speed up your application? Laravel's caching makes it simple.
    
I simply understand:
    
Suppose your app shows the top 10 popular songs that users vote for. Do you really need to check these 10 songs when everyone visits your website? If you want to cache query results for 10 minutes or an hour to accelerate your application, Laravel's caching Cache module can make your work very simple.

Well, from this passage, I have learned that this is fully in line with my current needs. Next, I just need to find the corresponding methods and APIs, one step at a time.

 

2. Learn related APIs

1. Continue to the above document, which is shown below:
By default, Laravel is configured to use the file system cache driver. it's ready to go out of the box with no configuration. the file system driver stores cached items as files in the cache directory. if you're satisfied with this driver, no other configuration is required. you're ready to start using it.
     
I simply understand:

By default, Laravel uses the file system as the cache driver, which can be used without configuration. The file system driver saves cached data to files in the cache directory, if you think it is appropriate, you don't need to do any other configuration to start using it.

Of course, this is also in line with my idea. In fact, I just want to cache the page as a static page file. When the user accesses the page again, it will be OK to directly output the cached static page, if you need more advanced features, you can also use other drivers, such as database drivers, memcached, and redis drivers, which are very powerful!

2. Check the use case and find the usage method.
    
Case document here: http://laravel.com/docs/cache/usage

It can be seen that there are get, put, forever, remember, has, forget and other methods in it. These methods can also be used in a way that can be basically done by "looking at the context".
The detailed instructions are provided in the usage documentation. I will not elaborate on the usage instructions at a glance. I will only discuss the instructions in the code.

 

III. Specific implementation
     
1. Code before my homepage

Class Home_Controller extends Base_Controller {

Public function get_index (){
$ Posts = Post: with ('user ')
-> Join ('users', 'users. ID', '=', 'posts. post_author ')
-> Order_by ('posts. created_at ', 'desc ')
-> Get (array ('posts. ID', 'posts. support ', 'posts. against', 'users. username', 'posts. post_author ', 'posts. post_title ', 'posts. post_body '));

$ Data = array ();

Foreach ($ posts as $ p ){
$ Data [] = array (
'Id' => $ p-> id,
'Support' => $ p-> support,
'Against' => $ p-> against,
'Username' => $ p-> username,
'Post _ author' => $ p-> post_author,
'Post _ title' => $ p-> post_title,
'Post _ body' => $ p-> post_body
);
  }

Return View: make ('Home. Index ')
-> With ('posts', $ data );
 }

}
This is the controller of my homepage. The function is to retrieve all the blog posts from the blog table and output the results. If no new blog posts are published, there is indeed a lot of unnecessary overhead to look up the table.


2. The code after my modification is as follows:

Class Home_Controller extends Base_Controller {

Public function get_index (){

// Add static cache support
// Cache immediately if no static page cache exists
If (! Cache: has ('staticpagecache _ home ')){
$ Data = array ();

$ Posts = Post: with ('user ')
-> Join ('users', 'users. ID', '=', 'posts. post_author ')
-> Order_by ('posts. created_at ', 'desc ')
-> Get (array ('posts. ID', 'posts. support ', 'posts. against', 'users. username', 'posts. post_author ', 'posts. post_title ', 'posts. post_body '));

Foreach ($ posts as $ p ){
$ Data [] = array (
'Id' => $ p-> id,
'Support' => $ p-> support,
'Against' => $ p-> against,
'Username' => $ p-> username,
'Post _ author' => $ p-> post_author,
'Post _ title' => $ p-> post_title,
'Post _ body' => $ p-> post_body
);
   }

$ Res = View: make ('Home. Index ')
-> With ('posts', $ data );

Cache: forever ('staticpagecache _ home', $ res );
  }

// Return the cached data
Return Cache: get ('staticpagecache _ home ');
 }

}

Three APIs are used here.
1). Cache: has, which indicates that if the name staticPageCache_home does not exist, the data will be retrieved immediately.

2 ). cache: forever. This document shows the meaning of "permanent Cache", because I usually work very hard. If I post a blog post, you just need to refresh the cache in the background, so you don't need to set the expiration time or the Expiration Time. Of course, this is based on your specific needs.

3). Cache: get, which is the Cache that extracts the name staticPageCache_home from the Cache and then returns the response content.

Well, it's that simple. Well, a basic cache function is complete, and laravel is really good!

3. Added the cache refresh function for the background.
Paste the code, but it is also very simple:

Public function get_refreshcache (){
/*
@ Var $ GID admin group id
*/
$ GID = 1;

If (Auth: user ()-> gid = 1 ){

$ Data = array ();

$ Posts = Post: with ('user ')
-> Join ('users', 'users. ID', '=', 'posts. post_author ')
-> Order_by ('posts. created_at ', 'desc ')
-> Get (array ('posts. ID', 'posts. support ', 'posts. against', 'users. username', 'posts. post_author ', 'posts. post_title ', 'posts. post_body '));

Foreach ($ posts as $ p ){
$ Data [] = array (
'Id' => $ p-> id,
'Support' => $ p-> support,
'Against' => $ p-> against,
'Username' => $ p-> username,
'Post _ author' => $ p-> post_author,
'Post _ title' => $ p-> post_title,
'Post _ body' => $ p-> post_body
);
        }

$ Res = View: make ('Home. Index ')
-> With ('posts', $ data );

Cache: forever ('staticpagecache _ home', $ res );

Return 'homepage cache refreshed successfully! ';
    }

Return 'Sorry, this operation can be performed only in the administrator group! ';
}

I added a project to the background. Corresponding to this method, the content of the method is similar to that of the home page. It is as simple as getting data and then Cache: forever refresh the Cache. Of course, the above Auth: user () judgment is a simple judgment. Only the administrator group can perform the refresh operation.

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.