Drupal7 cache development tutorial

Source: Internet
Author: User
Tags php file drupal drupal cache

Using Drupal to build complex and dynamic content is easy. However, if you are not careful, you will pay a price easily. When users view complex and dynamic pages, complex database queries and high-cost computing may cause page performance problems.

One solution is to enable page caching on the background page of Druapl. After the page cache is enabled, you can greatly reduce the number of database queries on some pages to improve page performance. But this has some limitations, that is, the page cache is only valid for anonymous users. The logon user takes effect.

Gradually, you may analyze the code you have written to find out the data query hotspots for cache optimization. Fortunately, Drupal already has some built-in cache APIs. If you follow the following rules, you can make code optimization easier.

Basic rules:

Rule: If the computing result can be reused or stored, do not calculate twice.

The following simple example is used to demonstrate this situation.

The code is as follows: Copy code
Function my_module_function (){
$ My_data = & drupal_static (_ FUNCTION __);
If (! Isset ($ my_data )){
// Write some high-end computing logic here and assign the result to the $ my_data variable.
  }
Return $ my_data;
}

Understanding the above code requires some basic php knowledge.

First, we know that php has a variable type of static variable ). The drupal_static function implements centralized management of static variables.

The second is to add the "&" symbol before the function, which is to pass the value by address. In this case, any changes to the $ my_data variable will be made to & drupal_static (_ FUNCTION.


After understanding these two points, let's look at the above logic and find that although there is only one if judgment, this code is actually very subtle.


Advanced: use Drupal's cache functions.

In the above code, the static variable data is valid only once during page loading. If you re-access the page, the data calculation will be performed again. That is to say, the data cached by static variables is temporary and cannot be stored for a long time. The following code demonstrates how to store complex computing result data in the drupal cache table for long-term storage.

The code is as follows: Copy code
Function my_module_function (){
$ My_data = & drupal_static (_ FUNCTION __);
If (! Isset ($ my_data )){
If ($ cache = cache_get ('My _ module_data ')){
$ My_data = $ cache-> data;
    }
Else {
// Write some high-end computing logic here and assign the result to the $ my_data variable.
// Save the calculation result to the cache table.
Cache_set ('My _ module_data ', $ my_data, 'cache ');
    }
  }
Return $ my_data;
}

The preceding example combines cache_set and cache_get to cache the calculated result data to the Drupal cache table. Complex computing is required during the first execution; however, when executing this code for the second time, the data content will be directly read from the cache table to avoid complicated computing overhead or database queries. This improves the efficiency of code execution once.


Cache Data Update

What if the cache data set in cache_set () mode expires? By default, the cache set by cache_set is stored in the database until you call the cache_clear_all () function to forcibly clear the cache (if the admin_menu module is installed, you can use the clear cache function provided by admin menu to clear the cache table ).

If your data is relatively fragmented, you can call cache_clear_all ('My _ module_data ', 'cache') to update the cache data each time you update the data. If you store some regular data fragments, you can clear the cache by using the wildcard as follows.

The code is as follows: Copy code

Cache_clear_all ('My _ module', 'cache', TRUE );

This method clears all caches starting with my_module.


If the expiration time of your cache is regular and predictable, you can try the following method to set the expiration time for the cache.

The code is as follows: Copy code

Cache_set ('My _ module_data ', $ my_data, 'cache', time () + 3600 );

The last parameter is a unix timestamp, indicating the cache expiration time. In this example, the cache expires after one hour, and the data in the cache is automatically discarded.


Customize your own cache table

During the code above, if you are careful, you will find that the third parameter "cache" of the cache_set () function actually represents the name of the cache data table. If you need to use a large number of caches, it is best to use an independent data table to store data in the cache; this will help speed up data query. The well-known views module uses this technology to implement its cache control policy.


The simplest and most Drupal-based custom cache table customization method is to execute hook_schema () in the install file of the module. The following is an example:

The code is as follows: Copy code
Function mymodule_schema (){
$ Schema ['cache _ mymodule'] = drupal_get_schema_unprocessed ('system', 'cache ');
Return $ schema;
}

In the above function, drupal_get_schema_unprocessed ('system', 'cache') is used to obtain the default Drupal cache table structure definition for cache_mymodule tables.

If you want to thoroughly squeeze the server's performance, you only need to add a small amount of code to the settings. Php file, you can replace the cache system of function calls such as Drupal cache_set and cache_get with other cache systems. For example, the popular memcache (memory-based cache with high efficiency) and APC (file-based cache. You only need to use the standard Drupal cache function, even if you have changed the cache system, you do not need to modify your code.

Notes:

1: Do not cache for cache. For example, querying a result from a database and writing a result to the database are lightweight operations and there is no need to use the cache. We recommend that you use the devel module to find and optimize code performance bottlenecks.

2: The data stored in the cache table is of the blob type. Do not perform join queries with the cache table.

3: remember that the cached data is not permanently stored. Any code that calls cache_clear_all will clear the cache. Therefore, data obtained through repeated computation cannot be stored in the cache table.


Come on, Drupalor!

Now, if you read this article carefully and digest it, congratulations: you have mastered a powerful tool to accelerate your code! Proceed and continue optimization!

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.