Example of using file cache in php
|
In web development, you can use file caching to greatly relieve the pressure on the database. The following code is an example of using file caching in php.
CacheLayer. php
- Class CacheLayer {
- Protected $ root = "";
- Protected $ cache = "";
- Protected $ key = "";
- Protected $ life = 0;
- Public function _ construct ($ key, $ root = "/cachelayer "){
- $ This-> root = $ _ SERVER ["DOCUMENT_ROOT"]. $ root;
- $ This-> key = $ key;
- }
- Public function expired ($ life_span ){
- $ This-> life = $ life_span;
- $ File = $ this-> root. "/". $ this-> key. ". cachelayer ";
- If (is_file ($ file )){
- $ Mtime = filemtime ($ file );
- Return (time () >=( $ mtime + $ this-> life ));
- } Else {
- Return true;
- }
- }
- Public function put ($ content ){
- $ File = $ this-> root. "/". $ this-> key. ". cachelayer ";
- If (! Is_dir (dirname ($ this-> root ))){
- Return false;
- }
- $ This-> delete ();
- $ Content = json_encode ($ content );
- Return (bool) file_put_contents ($ file, $ content );
- }
- Public function get (){
- $ File = $ this-> root. "/". $ this-> key. ". cachelayer ";
- If (is_file ($ file )){
- Return json_decode (file_get_contents ($ file), true );
- }
- Return array ();
- }
- Public function delete (){
- $ File = $ this-> root. "/". $ this-> key. ". cachelayer ";
- If (is_file ($ file )){
- Unlink ($ file );
- Return true;
- }
- Return false;
- }
- }
Example. php
- // Load the cachelayer and the database connection (db connection is optional)
- Require_once "CacheLayer. php ";
- Require_once "db_connection.php ";
- // Create a instance of the cachelayer
- $ Cl_nav = new CacheLayer ("navigation ");
- // Check to see if the cache is expired (60*10 = 10 minutes)
- If ($ cl_nav-> expired (60*10 )){
- Echo "Cache DOESN'T exist or is expired. Rebuilding...
";
- // If the cache is expired rebuild it
- $ Result = mysql_query ("select id, title from navigation ");
- $ New_cache = array ();
- While ($ row = mysql_fetch_assoc ($ result )){
- $ New_cache [] = $ row;
- }
- // Save the array into the cache
- $ Cl_nav-> put ($ new_cache );
- }
- Echo "Loading from cache...
";
- // Get the cache
- $ Cache = $ cl_nav-> get ();
- // Display the cache
- Foreach ($ cache as $ row ){
- $ Id = $ row ["id"];
- $ Title = $ row ["title"];
- Echo "$ title
";
- }
|
Php