<?php

class Storage extends Model
{

    function __construct($fromArray = array())
    {
        $this->_tableName_ = 'storage';
        parent::__construct($fromArray);
    }

    static function model()
    {
        return new self();
    }

    static function get($key)
    {
        $val = self::model()->getAll(array('where' => '(`key` = "'.  md5($key).'") AND (`ttl` >= '.time().')', 'limit' => 1));
        return $val ? unserialize($val->value) : NULL;
    }

	/**
	 *
	 * @param type $key
	 * @param type $value
	 * @param int $ttl seconds
	 * @return boolean
	 */
    static function set($key, $value, $ttl = 60)
    {
        $value = serialize($value);
        $ttl = time()+$ttl;

		$request = App::DB()->prepare("INSERT INTO `storage` SET `key`=?, `keyRaw` = ?, `value`=?, `ttl`=? ON DUPLICATE KEY UPDATE `value`=?, `ttl`=? ;");
		$res = $request->execute(array(md5($key), $key, $value, $ttl, $value, $ttl));

        return TRUE;
    }
}
