Chapter 4. Zend_Cache

Table of Contents

4.1. Introducere
4.2. The theory of caching
4.2.1. The Zend_Cache factory method
4.2.2. Tagging records
4.2.3. Cleaning the cache
4.3. Zend_Cache frontends
4.3.1. Zend_Cache_Core
4.3.2. Zend_Cache_Frontend_Output
4.3.3. Zend_Cache_Frontend_Function
4.3.4. Zend_Cache_Frontend_Class
4.3.5. Zend_Cache_Frontend_File
4.3.6. Zend_Cache_Frontend_Page
4.4. Zend_Cache backends
4.4.1. Zend_Cache_Backend_File
4.4.2. Zend_Cache_Backend_Sqlite
4.4.3. Zend_Cache_Backend_Memcached
4.4.4. Zend_Cache_Backend_APC
4.4.5. Zend_Cache_Backend_ZendPlatform

4.1. Introducere

Zend_Cache oferă un mod generic de a stoca temporar orice fel de date.

Stocarea temporară a datelor (caching) este operată în Zend Framework de interfeţe (frontend), în timp ce stocarea înregistrărilor se face prin adaptoare (backend adapters). (File, Sqlite, Memcache...) cu ajutorul unui sistem flexibil de ID-uri şi etichete. Folosind aceste adaptoare, vă va fi uşor să ştergeţi ulterior tipuri specifice de înregistrări (de exemplu: „şterge toate înregistrările memorate marcate cu o etichetă dată”).

Nucleul modulului (Zend_Cache_Core) este generic, flexibil şi configurabil. Totuşi, pentru nevoi specifice, există interfeţe care extind Zend_Cache_Core pentru convenienţă: Output, File, Function şi Class.

Example 4.1. Obţinerea unei interfeţe cu Zend_Cache::factory()

Zend_Cache::factory() creează instanţe ale obiectelor şi face legătura între ele. În acest prim exemplu, vom folosi interfaţa Core împreună cu adaptorul File .

<?php
require_once 'Zend/Cache.php';

$frontendOptions = array(
<<<<<<< .mine
   'lifeTime' => 7200, // timp de viaţă pentru înregistrări de 2 ore
=======
   'lifetime' => 7200, // cache lifetime of 2 hours 
>>>>>>> .r4254
   'automaticSerialization' => true
);

$backendOptions = array(
    'cacheDir' => './tmp/' // Directorul unde se pun fişierele cache
);

// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

?>

Acum că avem o interfaţă, putem stoca orice tip de date (am pornit serializarea). De exemplu, putem stoca un rezultat al unei interogări foarte complexe în baza de date. După ce este stocat, nu mai este nevoie nici măcar să ne conectăm la baza de date; înregistrările sunt preluate din Now that we have a frontend, we can cache any type of data (we turned on serialization). For example, we can cache a result from a very expensive database query. After it is cached, there is no need to even connect to the database; records are fetched from cache and unserialized.

<?php

// $cache initialized in previous example

// see if a cache already exists:
if(!$result = $cache->load('myresult')) {

    // cache miss; connect to the database
    
    $db = Zend_Db::factory( [...] );
    
    $result = $db->fetchAll('SELECT * FROM huge_table');
    
    $cache->save($result, 'myresult');
    
} else {

    // cache hit! shout so that we know
    echo "This one is from cache!\n\n";
    
}

print_r($result);

?>

Example 4.2. Caching output with Zend_Cache output frontend

We 'mark up' sections in which we want to cache output by adding some conditional logic, encapsulating the section within start() and end() methods (this resembles the first example and is the core strategy for caching).

Inside, output your data as usual - all output will be cached when execution hits the end() method. On the next run, the whole section will be skipped in favor of fetching data from cache (as long as the cache record is valid).

<?php

$frontendOptions = array(
   'lifetime' => 30,                  // cache lifetime of half a minute
   'automaticSerialization' => false  // this is default anyway
);

$backendOptions = array('cacheDir' => './tmp/');

$cache = Zend_Cache::factory('Output', 'File', $frontendOptions, $backendOptions);

// we pass a unique identifier to the start() method
if(!$cache->start('mypage')) {
    // output as usual:
    
    echo 'Hello world! ';
    echo 'This is cached ('.time().') ';
    
    $cache->end(); // the output is saved and sent to the browser
}

echo 'This is never cached ('.time().').';

?>       

Notice that we output the result of time() twice; this is something dynamic for demonstration purposes. Try running this and then refreshing several times; you will notice that the first number doesn't change while second changes as time passes. That is because the first number was output in the cached section and is saved among other output. After half a minute (we've set lifetime to 30 seconds) the numbers should match again because the cache record expired -- only to be cached again. You should try this in your brower or console.

[Note] Note

When using Zend_Cache, pay attention to the important cache identifier (passed to save() and start()). It must be unique for every resource you cache, otherwise unrelated cache records may wipe each other or, even worse, be displayed in place of the other.