Status
Not open for further replies.

dude

Active Member
26
2010
0
0
hello

just started learning OOP yesterday and created my first class today:

PHP:
<?php
class Database extends PDO
{

	private $host;
	private $user;
	private $password;
	private $name;
	private $cache_dir;
	public $cache_result = array();

	public function __construct($host, $user, $password, $name, $cache_dir)
	{
		$this->host = $host;
		$this->user = $user;
		$this->password = $password;
		$this->name = $name;
		$this->cache_dir = $cache_dir;
		
		try
		{
			parent::__construct('mysql:host='.$this->host.';dbname='.$this->name, $this->user, $this->password);
		}
		catch (Exception $e)
		{
			die('Error: ' . $e->getMessage());
		}
	}

	function cache($sql, $cache_time=0)
	{

		$digest = md5($sql);
		$cache_path = $this->cache_dir.'sql_'.$digest.'.txt';
			
		if(file_exists($cache_path)) // If the cache already exists...
		{
			$cache_date = filemtime($cache_path); // Gets cache time
			$now = time();
			$cache_age = $now - $cache_date;
			
			if($cache_age > $cache_time) // If the cache is outdated, we recreate it...
			{
				$q = parent::prepare($sql);
				$q->execute();
				$this->cache_result = $q->fetchAll();
				$f = serialize($this->cache_result); // Array to string
				file_put_contents($cache_path, $f);
			}
			else // sinon on le lit
			{
				$buff = file_get_contents($cache_path);
				$this->cache_result = unserialize($buff);
			}
		}
		else // else we create it
		{
			$q = parent::prepare($sql);
			$q->execute();
			$this->cache_result = $q->fetchAll();
			$f = serialize($this->cache_result); // Array to string
			file_put_contents($cache_path, $f);
		}
	}

	public function get_cache_result()
	{
		return $this->cache_result;
	}
	
	
}



$db = new Database('localhost', 'root', '', 'forum', 'cache/');
$db->cache('SELECT * FROM bbs_posts WHERE post_id = 501', 300);
$res = $db->get_cache_result();
echo '<pre>';
print_r($res);
echo '</pre>';
?>

so what do you think ? help me to improve it and learn more things :)
 
1 comment
well firstly why are you attempting to cache quires before there complete, make sure you cover every error possible so what your code should be doing is.

PHP:
$db = new Database('localhost', 'root', '', 'forum', 'cache/');
$sql = 'SELECT * FROM bbs_posts WHERE post_id = 501';

$res = (!$db->is_cached($sql) ? $db->query($sql,true) : $db->get_cache_result($sql));

foreach($res as $id => $entity)
{
    //..
}

you will notice that there's a second param within query as this could be used to catch on success, so less user code.

but your concept is good, does exactly what you need it to do
 
Status
Not open for further replies.
Back
Top