2.3. Zend_Cache frontends
Poprzedni | Rozdział 2. Zend_Cache | Następny

## 2.3. Zend_Cache frontends

### 2.3.1. Zend_Cache_Core

#### 2.3.1.1. Introduction

`Zend_Cache_Core` is a special frontend because it is the core of the module. It is a generic cache frontend and is extended by other classes.

| Notatka
All frontends inherit from `Zend_Cache_Core` so that its methods and options (described below) would also be available in other frontends, therefore they won't be documented there.

#### 2.3.1.2. Available options

These options are passed to the factory method as demonstrated in previous examples.

Tabela 2.1. Available options

Option | Data Type | Default Value | Description
--- | --- | --- | ---
`caching` | `boolean` | `true` | enable / disable caching (can be very usefull for the debug of cached scripts)
`lifeTime` | `int` | `3600` | cache lifetime (in seconds), if set to `null`, the cache is valid forever.
`logging` | `boolean` | `false` | if set to true, logging through `Zend_Log` is activated (but the system is slower)
`writeControl` | `boolean` | `true` | Enable / disable write control (the cache is read just after writing to detect corrupt entries), enabling writeControl will lightly slow the cache writing but not the cache reading (it can detect some corrupt cache files but it's not a perfect control)
`automaticSerialization` | `boolean` | `false` | Enable / disable automatic serialization, it can be used to save directly datas which aren't strings (but it's slower)
`automaticCleaningFactor` | `int` | `0` | Disable / Tune the automatic cleaning process (garbage collector): 0 means no automatic cache cleaning, 1 means systematic cache cleaning and x > 1 means automatic random cleaning 1 times in x write operations.

#### 2.3.1.3. Examples

An example is given in the manual at the very beginning.

If you store only strings into cache (because with "automaticSerialization" option, it's possible to store some booleans), you can use a more compact construction like:

    <?php

    // we assume you already have $cache

    $id = 'myBigLoop'; // cache id of "what we want to cache"

    if (!($data = $cache->get($id))) {
        // cache miss

        $data = '';
        for ($i = 0; $i < 10000; $i++) {
            $data = $data . $i;
        }

        $cache->save($data);

    }

    // [...] do something with $data (echo it, pass it on etc.)

    ?>

If you want to cache multiple blocks or data instances, the idea is the same:

    <?php

    // make sure you use unique identifiers:
    $id1 = 'foo';
    $id2 = 'bar';

    // block 1
    if (!($data = $cache->get($id1))) {
        // cache missed

        $data = '';
        for ($i=0;$i<10000;$i++) {
            $data = $data . $i;
        }

        $cache->save($data);

    }
    echo($data);

    // this isn't affected by caching
    echo('NEVER CACHED! ');

    // block 2
    if (!($data = $cache->get($id2))) {
        // cache missed

        $data = '';
        for ($i=0;$i<10000;$i++) {
            $data = $data . '!';
        }

        $cache->save($data);

    }
    echo($data);

    ?>

### 2.3.2. Zend_Cache_Frontend_Output

#### 2.3.2.1. Introduction

`Zend_Cache_Frontend_Output` is an output-capturing frontend. It utilizes output buffering in PHP to capture everything between its `start()` and `end()` methods.

#### 2.3.2.2. Available options

This frontend doesn't have any specific options other than those of `Zend_Cache_Core`.

#### 2.3.2.3. Examples

An example is given in the manual at the very beginning. Here it is with minor changes:

    <?php

    // if it is a cache miss, output buffering is triggered
    if(!$cache->start('mypage')):

    // output everything as usual
    echo 'Hello world! ';
    echo 'This is cached ('.time().') ';

    $cache->end(); // output buffering ends
    endif;

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

    ?>

Using this form it is fairly easy to set up output caching in your already working project with little or no code refactoring.

### 2.3.3. Zend_Cache_Frontend_Function

#### 2.3.3.1. Introduction

`Zend_Cache_Frontend_Function` caches the results of function calls. It has a single main method named `call()` which takes a function name and parameters for the call in an array.

#### 2.3.3.2. Available options

Tabela 2.2. Available options

Option | Data Type | Default Value | Description
--- | --- | --- | ---
`cacheByDefault` | `boolean` | `true` | if true, function calls will be cached by default
`cachedFunctions` | `array` |  | function names which will always be cached
`nonCachedFunctions` | `array` |  | function names which must never be cached

#### 2.3.3.3. Examples

Using the `call()` function is the same as using `call_user_func_array()` in PHP:

    <?php

    $cache->call('veryExpensiveFunc', $params);

    # $params is an array
    # for example to call (with caching) veryExpensiveFunc(1, 'foo', 'bar'), you will use
    # $cache->call('veryExpensiveFunc', array(1, 'foo', 'bar'))

    ?>

`Zend_Cache_Frontend_Function` is smart enough to cache both the return value of the function and its internal output.

| Notatka
You can pass any builtin or user defined function with the exception of `array()`, `echo()`, `empty()`, `eval()`, `exit()`, `isset()`, `list()`, `print()` and `unset()`.

### 2.3.4. Zend_Cache_Frontend_Class

#### 2.3.4.1. Introduction

`Zend_Cache_Frontend_Class` is different from `Zend_Cache_Frontend_Function` because it allows caching of object and static method calls.

#### 2.3.4.2. Available options

Tabela 2.3. Available options

Option | Data Type | Default Value | Description
--- | --- | --- | ---
`cachedEntity` (required) | `mixed` |  | if set to a class name, we will cache an abstract class and will use only static calls; if set to an object, we will cache this object methods
`cacheByDefault` | `boolean` | `true` | if true, calls will be cached by default
`cachedMethods` | `array` |  | method names which will always be cached
`nonCachedMethods` | `array` |  | method names which must never be cached

#### 2.3.4.3. Examples

For example, to cache static calls :

    <?php

    class test {

        # Static method
        public static function foobar($param1, $param2) {
            echo "foobar_output($param1, $param2)";
            return "foobar_return($param1, $param2)";
        }

    }

    // [...]
    $frontendOptions = array(
        'cachedEntity' => 'test' // The name of the class
    );
    // [...]

    # The cached call
    $res = $cache->foobar('1', '2');

    ?>

To cache classic method calls :

    <?php

    class test {

        private $_string = 'hello !';

        public function foobar2($param1, $param2) {
            echo($this->_string);
            echo "foobar2_output($param1, $param2)";
            return "foobar2_return($param1, $param2)";
        }

    }

    // [...]
    $frontendOptions = array(
        'cachedEntity' => new test() // An instance of the class
    );
    // [...]

    # The cached call
    $res = $cache->foobar2('1', '2');

    ?>

### 2.3.5. Zend_Cache_Frontend_File

#### 2.3.5.1. Introduction

`Zend_Cache_Frontend_File` is a frontend driven by the modification time of a "master file". It's really interesting for examples in configuration or templates issues.

For instance, you have an XML configuration file which is parsed by a function which returns a "config object" (like with `Zend_Config`). With `Zend_Cache_Frontend_File`, you can store the "config object" into cache (to avoid the parsing of the XML config file at each time) but with a sort of strong dependency on the "master file". So, if the XML config file is modified, the cache is immediatly invalidated.

#### 2.3.5.2. Available options

Tabela 2.4. Available options

Option | Data Type | Default Value | Description
--- | --- | --- | ---
`masterFile (mandatory)` | `string` | `` | the complete path and name of the master file

#### 2.3.5.3. Examples

Use of this frontend is the same than of `Zend_Cache_Core`. There is no need of a specific example - the only thing to do is to define the `masterFile` when using the factory.

### 2.3.6. Zend_Cache_Frontend_Page

#### 2.3.6.1. Introduction

`Zend_Cache_Frontend_Page` is like `Zend_Cache_Frontend_Output` but designed for a complete page. It's impossible to use `Zend_Cache_Frontend_Page` for caching only a single block.

On the other hand, the "cache id" is calculated automatically with `$_SERVER['REQUEST_URI']` and (depending on options) `$_GET`, `$_POST`, `$_SESSION`, `$_COOKIE`, `$_FILES`. More over, you have only one method to call (`start()`) because the `end()` call is fully automatic when the page is ended.

For the moment, it's not implemented but we plan to add a HTTP conditional system to save bandwith (the system will send a HTTP 304 Not Modified if the cache is hit and if the browser has already the good version).

| Notatka
Zend_Cache_Frontend_Page is really "alpha stuff" and is meant to be improved further down the road.

#### 2.3.6.2. Available options (for this frontend in Zend_Cache factory)

Tabela 2.5. Available options

Option | Data Type | Default Value | Description
--- | --- | --- | ---
`httpConditional` | `boolean` | `false` | use the httpConditional system (not implemented for the moment)
`cacheWith{Get,Post,Session,Files,Cookie}Variables` | `boolean` | `false` | if true, cache is still on even if there are some variables in the corresponding superglobal array ; if false, cache is off if there are some variables in the corresponding superglobal array
`makeIdWith{Get,Post,Session,Files,Cookie}Variables` | `boolean` | `true` | if true, we have to use the content of the corresponding superglobal array to make a cache id if false, the cache id won't be dependent of the content of the corresponding superglobal array

#### 2.3.6.3. Examples

Use of Zend_Cache_Frontend_Page is really trivial :

    <?php

    // [...] // require, configuration and factory

    $cache->start();
    # if the cache is hit, the result is sent to the browser and the script stop here

    // rest of the page ...

    ?>

Poprzedni | Początek rozdziału | Następny
2.2. The theory of caching | Spis treści | 2.4. Zend_Cache backends