Skip to content
This repository

Engine 

marcelklehr edited this page · 5 revisions
Clone this wiki locally

Zoocache provides throw-in caching engine, to easily add a caching layer to already existing sites.

To initialize this engine on your page, use Zoo\Engine::init(). init creates the key, which is used to cache the current page. For this, it takes the following flags:

  • USE_SCHEME
  • USE_DOMAIN
  • USE_PATH
  • USE_GETVARS

Every URL that produces the same key, based on the flags your passed, will provide the same content. E.g. if you USE_SCHEME, a page, which is accessed through http is stored in a different cache entry than the same page accessed through https. You will always want to USE_PATH!

<?php
$engine = Zoo\Engine::init(Zoo\USE_PATH|Zoo\USE_GETVARS);
?>

You can also use a callback to init, which is then expected to return the key to be used for the page. This enables you, for example, to use the value of specific cookie, so that all users with the same cookie value see the same page.

Now you can use the following modifiers:

compress uses gzip to compress the contents of your page before thy are sent.

<?php
$engine->compress();
?>

expireIn set the time in seconds, until the cache entry will expire and the page has to be recached.

<?php
$engine->expireIn(20);
?>

setBlacklist takes an array of regular expressions, if one of them matches, the page will not be cached.

<?php
$engine->setBlacklist(array(
  '~\?nocache$~'// prevent caching if ?nocache is appended to the URL
));
?>

filter takes a callback, which is invoked, passing the contents of the page, that is about to be cached. If it is not false, the return value of the callback will be used to store in the cache entry, instead.

<?php
// minimize html!
$engine->filter(function($content) {
    $search = array(
        '/>[^\S ]+/s', // strip whitespaces AFTER html tags, except non-whitespace
        '/[^\S ]+</s', // strip whitespaces BEFORE html tags, except non-whitespace
        '/(\s)+/s'      // shorten multiple whitespace sequences
    );
    $replace = array(
        '>',
        '<',
        '\\1'
    );
  $content = preg_replace($search, $replace, $content);
  return $content;
});
?>

In order to activate caching on your page, you will eventually have to call run.

<?php
$engine->run();
?>

Put together, it looks like this.

<?php
Zoo\Engine::init(Zoo\USE_PATH|Zoo\USE_GETVARS)
    ->compress()
    ->expireIn(20)
    ->setBlacklist(array(
    '~\?nocache$~'
    ))
->run();
?>

You can throw this into a single file and use Apache's auto_prepend directive in your .htaccess file, to automatically include it: php_value auto_prepend_file bootstrap.php.

Encoding error?

If your browser can't view the page and reports an encoding error, there's probably a PHP error messing up the gzip encoding. Turning off gzip compression should enable you to see the error.

Something went wrong with that request. Please try again.