<?php
/**
* Crutch Cache
* Class for saving data to a text file.
*
* @date 01/06/2010
* @author Ladislav Vondracek, http://www.twitter.com/Lawondyss
* @copyright 2010 Ladislav Vondracek
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
class CrutchCache
{
/**
* Filepath to file with data
*
* @var string filepath
*/
private $storage;
/**
* Array of loaded data
*
* @var array loaded variables
*/
private $variables;
/**
* File pointer opened storage file
*
* @var resource file stream
*/
private $fp;
/**
* Constructor
*
* @param string $file File name for storage data
* @param string $dir Dir with file
*/
public function __construct($file, $dir='temp/')
{
// added slash at the endof the directory name
if(substr($dir, -1) != '/')
{
$dir .= '/';
}
// create a non-existing directory and settings permissions
if(!is_dir($dir))
{
mkdir($dir, 0700, TRUE);
}
// filepath
$this->storage = $dir.$file.'.cc';
// loaded data if the file exists
if(is_file($this->storage))
{
// serialized string
$serialized = file_get_contents($this->storage);
// unserialized
$this->variables = unserialize($serialized);
if(!is_array($this->variables))
{
$this->error('Cache "'.$file.'" is probably already open somewhere before.', E_USER_ERROR, debug_backtrace());
}
}
// file does not exist
else
{
// empty array
$this->variables = array();
}
// create/overwrite the file for write
$this->fp = fopen($this->storage, 'w');
}
/**
* Destructor
*/
public function __destruct()
{
if($this->fp)
{
// serialized data
$serialized = serialize($this->variables);
// write to the file
fwrite($this->fp, $serialized);
// close the file
fclose($this->fp);
}
}
/**
* Magical method to retrieve the stored variable
*
* @param string $name Variable name
* @return mixed Variable value
*/
public function __get($name)
{
// only if variable exists
if(array_key_exists($name, $this->variables))
{
return $this->variables[$name];
}
else
{
$this->error('Variable "'.$name.'" was not created.', E_USER_ERROR, debug_backtrace());
}
}
/**
* Sets the variable to store
*
* @param string $name Variable name
* @param mixed $value Variable value
*/
public function __set($name, $value)
{
$this->variables[$name] = $value;
}
/**
* Deletes one or all values
*
* @param string $name Variable name
* @internal if $name is NULL, delete all
* @return bool Deleted
*/
public function delete($name=NULL)
{
if(is_null($name))
{
$this->variables = array();
return TRUE;
}
elseif(array_key_exists($name, $this->variables))
{
unset($this->variables[$name]);
return TRUE;
}
else
{
return FALSE;
}
}
/**
* Returns all variables
*
* @return array All variables
*/
public function all()
{
return $this->variables;
}
private function error($message, $type, $backtrace)
{
$backtrace = array_shift($backtrace);
$head = basename($backtrace['file']).'['.$backtrace['line'].']: ';
trigger_error($head.$message, $type);
}
}