PHP code example of stefangabos / zebra_cache

1. Go to this page and download the library: Download stefangabos/zebra_cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

stefangabos / zebra_cache example snippets


// make sure you have this at the top of your script
use stefangabos\Zebra_Cache\Zebra_Cache;
use stefangabos\Zebra_Cache\Storage\Storage_File;

// initialize file-based storage
$storage = new Storage_File('/path/to/cache/folder');

// make sure you have this at the top of your script
use stefangabos\Zebra_Cache\Zebra_Cache;
use stefangabos\Zebra_Cache\Storage\Storage_Redis;

// connect to a Redis server
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// pass the $redis instance as argument to initialize the Redis-based storage
$storage = new Storage_Redis($redis);

// finally, instantiate the caching library using the storage engine configured above
$cache = new stefangabos\Zebra_Cache\Zebra_Cache($storage);

// make sure you have this at the top of your script
use stefangabos\Zebra_Cache\Zebra_Cache;
use stefangabos\Zebra_Cache\Storage\Storage_Memcached;

// connect to a Memcached server (using the `memcached` extension)
$memcache = new Memcached();
$memcache->addServer('localhost', 11211);

// OR using the `memcache` extension
$memcache = new Memcache();
$memcache->addServer('localhost', 11211);

// pass the $memcache instance as argument to initialize the Memcached-based storage
$storage = new Storage_Memcached($memcache);

// instantiate the caching library using the chosen storage engine
$cache = new Zebra_Cache($storage);

// if a cached, non-expired value for the sought key does not exist
if (!($my_data = $cache->get('my-key'))) {

    // do whatever you need to retrieve data
    $my_data = 'my data';

    // cache the values for one 10 minutes (10 x 60 seconds)
    $cache->set('my-key', $my_data, 10 * 600);

}

// at this point $my_data will always contain data, either from cache, or fresh

if ($info = $cache->has('my-key')) {

    print_r('<pre>');
    print_r($info);

    // for file-based storage the output will look something like
    // [
    //  'path'     => '',  //  path to the cache file
    //  'timeout'  => '',  //  the number of seconds the cache was supposed to be valid
    //  'ttl'      => '',  //  number of seconds remaining until the cache expires
    // ]

}

$cache->delete('my-key');