PHP Classes

File: CacheTest.php

Recommend this page to a friend!
  Classes of Andrei Alexandru   Simple Cache System   CacheTest.php   Download  
File: CacheTest.php
Role: Example script
Content type: text/plain
Description: Usage and testing
Class: Simple Cache System
Store and retrieve cached data in MySQL and files
Author: By
Last change:
Date: 7 years ago
Size: 1,330 bytes
 

Contents

Class file image Download
<?php

require 'Atto/Cache/Cache.php';
require
'Atto/Cache/Item.php';
require
'Atto/Cache/Storage.php';
require
'Atto/Cache/Storage/FileStorage.php';
require
'Atto/Cache/Storage/NullStorage.php';

use
Atto\Cache\Cache;
use
Atto\Cache\storage\FileStorage;
use
Atto\Cache\storage\NullStorage;

// Some configuration
$useCache = true;

if (
$useCache === true) {
   
// You MUST use a non-public directory for this.
   
$storage = new FileStorage(__DIR__);
} else {
   
// Null storage doesn't save anything
    // Always return's a null value when you call $cache->get($key) method.
   
$storage = new NullStorage();
}

$cache = new Cache($storage, 60); // By default all items have 60 seconds of time to live

// Store new items
$cache->store('some.id.key', $data); // $data will live for 60 seconds (default - Cache constructor)
$cache->store('another.key', $data, 60 * 60 * 24 * 7); // Now $data will live for 7 days
$cache->store('forever', $data, 0); // Using a $ttl less than 1 will indicate that this item never expires

// Retrieve items from the cache
$data = $cache->get('some.id.key');

if (
$data === null) {
   
// $data does not exist in the cache storage
   
$data = ['foo', 'bar', 'baz'];
}

// Invalidate data
$cache->invalidate('another.key'); // This will remove an item from the cache storage