hello
just started learning OOP yesterday and created my first class today:
so what do you think ? help me to improve it and learn more things
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