PHP Classes

File: Atto/Cache/Cache.php

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

Contents

Class file image Download
<?php
namespace Atto\Cache;

/**
 * Simple extensible cache system
 *
 * @package Atto
 *
 * @namespace Atto\Cache
 * @name Atto\Cache\Cache
 * @author Andrei Alexandru Romila
 * @version v1.0
 */
class Cache {
   
   
/**
     * Storage engine
     *
     * @var Storage
     */
   
protected $storage;
   
   
/**
     * Time to live (default value)
     *
     * @var integer Time to live in seconds
     */
   
protected $ttl;

   
/**
     * Default constructor
     *
     * @param Storage $storage Storage engine
     * @param int $ttl Time to live in seconds (ttl less than or equal to 0 means no expiration)
     */
   
public function __construct(Storage $storage, $ttl = 0) {
       
$this->storage = $storage;
       
$this->ttl = $ttl;
    }

   
/**
     * Returns the data for the indicated $key or null if was not found or expired
     *
     * @param string $key
     *
     * @return mixed|NULL The data saved for the key or null if is expired or not found
     */
   
public function get($key) {
       
       
$item = $this->storage->getItem($key);
       
        if (
$item === null || $item->expired()) {
           
$this->invalidate($key);
           
            return
null;
        }
       
        return
$item->getData();
    }
   
   
/**
     * Stores a new item
     *
     * @param string $key The name of the item
     * @param mixed $object The data to store
     * @param integer $ttl Time to live in seconds, using less than 1 means no expiration
     */
   
public function store($key, $object, $ttl = null) {
       
       
// If no seconds are passed we use the default value
       
if ($ttl === null) {
           
$ttl = $this->ttl;
        }
       
       
// Create a new item
       
$item = new Item($object, $ttl);
       
       
// Store
       
$this->storage->save($key, $item);
    }
   
   
/**
     * Invalidates the indicated item
     *
     * @param string $key The name of the item
     */
   
public function invalidate($key) {
       
$this->storage->delete($key);
    }
}