PHP content cache output

Source: Internet
Author: User
Tags apc http cookie
Next we will start to explore more common cache Technologies, which is also the key part of this article. First, we use the cache package in PEAR. PEAR can cache content in files, databases, or memory. We use the file as an example to install PEAR cache.
/Usr/ports/sysutils/pear-Cache
Make install clean


◆ Content cache output PEAR cache


Next we will start to explore more common cache Technologies, which is also the key part of this article. First, we use the cache package in PEAR. PEAR can cache content in files, databases, or memory. We use files as an example.


Below is a PHP applet that does not use the cache:


Pear_content_cache1.php


<? Php
Echo "this is the content.

";
Echo "the current time is". date ('M-d-y h: I: s A', time ())."
";
?>


The above program is very simple. Now we add cache for it.
Pear_content_cache2.php


<? Php
 
Require_once 'cache/Output. php ';
 
// Set the cache directory, which must be writable.
$ CacheDir = './pear_cache ';
$ Cache = new Cache_Output ('file', array ('cache _ dir' => $ cacheDir ));
 
// If the nocache variable is empty, use the content in the cache.
// If you want to obtain the latest content, assign the value to the nocache variable.
If (empty ($ _ REQUEST ['nocache'])
{
// Create a unique cache ID
// Request + Cookie information
$ Cache_id = $ cache-> generateID (array ('URL' = >$ _ REQUEST, 'post' = >$ _ post, 'Cookies '= >$ HTTP_COOKIE_VARS ));
}
Else
{
// If you want to obtain the latest content, the ID is blank.
$ Cache_id = null;
}
 
 
// Check whether the cache content corresponding to the cache ID is available
If ($ content = $ cache-> start ($ cache_id ))
{
// Cache already exists, output directly, and end the script
Echo $ content;
Exit ();
}
 
// This content does not exist in the cache. new content is generated and written to the cache.
Echo "this is the content.

";

Echo "the current time is". date ('M-d-y h: I: s A', time ())."
";

 

// Write the content to the cache

Echo $ cache-> end ();

?>




Refresh the two files respectively. you will find that the time in the "current time is" line in pear_content_cache1.php changes with the refresh, while the time in pear_content_cache2.php remains unchanged. This is because pear_content_cache2.php uses the cache to store the content requested by the user into a static file. When the user requests again, it directly outputs the content from the file, instead of using the program to dynamically generate the content.
For pear_content_cache2.php, if you want to read the latest information, rather than cache the old information. You can use http ://... /Pear_content_cache2.php? Nocache = 1. this will disable the cache function. Refresh the page and you will find that the time changes accordingly.


To sum up the usage of the PEAR content cache class:


1. note the correct path when the PEAR package is included.


2. cache class included in Output. php


Require_once 'cache/Output. php ';
3. set cache Directory


$ CacheDir = './pear_cache ';
Make sure the directory is writable. The Cache data will be written into the subdirectory of this directory.


4. create an output cache object


$ Cache = new Cache_Output ('file', array ('cache _ dir' => $ cacheDir ));


The first parameter indicates that we use the file-based cache, and the second parameter is an array associated with the cache directory.
5. generate a unique cache ID


$ Cache_id = $ cache-> generateID (array ('URL' = >$ _ REQUEST, 'post' = >$ _ post, 'Cookies '= >$ HTTP_COOKIE_VARS ));


Here, the generateID () method of the $ cache object uniquely identifies this request by providing an information array (URL, http post data, and HTTP cookie), which is differentiated from other requests.
6. add a logical judgment statement to check whether the cache data corresponding to cacheID already exists. if so, obtain the data and end the script.


If ($ content = $ cache-> start ($ cache_id ))
{Echo $ content;
Exit ();
}


7. Place the code of the generated content after the preceding logic statement and end the use of the cache object.
Echo $ cache-> end ();


◆ Function cache output PEAR cache
In addition to caching the output content, PEAR can also cache the call results of a function. This is a very interesting feature. if your program needs to use a function frequently and the call results are the same, I suggest you try it, especially when this function runs slowly.


Below we implement a buffer call to a function slowFunction () that is executed very slowly.


<? Php
Require_once 'cache/Function. php ';
 
$ CacheDir = './pear_cache /';
$ Cache = new Cache_Function ('file', array ('cache _ dir' => $ cacheDir ));
$ Arr = array ('apple', 'Lil', 'watermelon ');
$ Cache-> call ('slowfunction', $ arr );
Echo'
';
 
$ Arr = array ('apple', 'Lil', 'watermelon ');
SlowFunction ($ arr );
 
Function slowFunction ($ arr = null)
{
Echo "a function that is very slow to execute :(
";
Echo "current time is". date ('M-d-y h: I: s A', time ()).'
';
Foreach ($ arr as $ fruit)
{
Echo "I ate a $ fruit
";
}
}
?>


The execution result of the sample script is as follows:
A function that is very slow to execute
Current time is Jul-28-2004 17:15:57
I ate an apple
I ate a pear.
I ate a watermelon.


A function that is very slow to execute
Current time is Jul-28-2004 17:17:55
I ate an apple
I ate a pear.
I ate a watermelon.


In the code, the Cache/Function. php class is used to execute the Function buffer Function. $ Cache variable is a Cache_Function object. it is saved to the $ cacheDir Directory using file-based function caching. To cache a function call, use the call () method of the Cache_Function object $ cache as follows: $ cache-> call ('slowfunction', $ arr );
Here, the slowFunction () function is called and the parameter is an array $ arr, which is cached in a file under the $ cacheDir directory. Any subsequent call to this function will return the execution result of this function by $ cache-> call.
Function caching is similar to content caching. For more information, see the PEAR manual.


All of the above uses the optimization code method to speed up the program. next we should take a look at another field of PHP acceleration-cache tool software. This type of software is accelerated by optimizing the PHP runtime environment without changing any code. We can refer to them as "execution code optimization/cache tools". you can refer to them for lower-layer optimization/caching.


The following lists the commonly used tools. use your own server environment to test the effect:
(1) APC Alternative PHP Cache
Http://apc.communityconnect.com/
APC runs on Linux and FreeBSD. you need to compile and install it yourself. According to their developers, the script speed can be increased by 50%-400% in their testing environment. APC is an open-source project that has been added to the PECL library of PHP. it is worth a try.
(2) Turck MMCache
Http://turck-mmcache.sourceforge.net/
Turck MMCache seems to be the most popular among such software. it is open-source and completely free of charge. It pre-compiles and caches PHP code and optimizes the PHP runtime environment. According to the official documentation, MMCache can significantly reduce the server load and increase the script execution speed by 1-10 times.
MMCache is compatible with another well-known acceleration software Zend Optimizer, but note that MMCache must be installed first (set in php. ini ). In addition to accelerating PHP programs, MMCache can also encrypt PHP code.
Turck MMCache supports both Linux and Win32 platforms.
(3) PHPA the PHP Accelerator
Http://www.php-accelerator/
PHPA is another popular PHP acceleration software. On its official website, PHP scripts using PHPA, APC, and Zend Cache are used for test comparison, which is slightly better than APC and slightly inferior to Zend Cache.
PHPA supports Linux, FreeBSD, OpenBSD, BSDi, and Solaris systems.
(4) Zend Performance Suite
Http://www.zend.com/
Zend Performance Suite is a well-established PHP acceleration/optimization software based on Zend, the most well-known PHP Company. Version 4.0 has been released, which can provide program acceleration, content caching, file compression, and download services for PHP applications. it has powerful functions and won several PHP magazine recommendation awards-but I have to mention it, it is also expensive. The current price is USD 1875.
The above acceleration software is expected to be tested by the reader based on the server environment and select the most suitable one, because I have no way to provide a universally applicable test standard to determine which solution is the most effective. In summary, I personally think Turck MMCache is a recommendable option. it is free of charge and has excellent functions.


(Iv) summary


The above describes PHP acceleration technologies in a comprehensive and meticulous manner from multiple perspectives, including testing and acceleration technologies (compression and caching). code and examples are provided. I hope this article will help readers fully understand PHP program acceleration and select an appropriate acceleration solution in practical applications.

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.