Ici la classe de base Item
<?php
class Item{
protected $id;
protected $log;
protected $db;
public function __construct($id){
$this->log=Log::getInstance();
$this->db = MySQLDataBase::getInstance();
$this->log->Trace('Item::__construct');
if($id!=NULL){
$this->id=$id;
}else $this->id=NULL;
}
public function getId(){
return $this->id;
}
public function setId($value){
$this->log->Trace('Item::setId - value :'.$value);
$this->id=$value;
}
protected function saveToCache(){
if($this->id!=NULL){
$cache=new Cache(get_class($this), $this->id);
$cache->set($this);
}
}
public function Load(){
$this->log->Trace('Item::Load');
$this->log->Trace('Not implemented');
}
public function WakeUpFromCache(){
$this->db=MySQLDataBase::getInstance();
$this->log=Log::getInstance();
}
public function __destruct() {
$this->prepareToSleep();
$this->saveToCache();
}
public function Free(){
$this->__destruct();
}
public function prepareToSleep(){
$this->db=NULL; //can't be serialized, cause Fatal error: Exception thrown without a stack frame in Unknown on line 0
$this->log=NULL;
}
}
?>
Ici ItemFactory
<?php
class ItemFactory{
private $log;
public function __construct(){
$this->log = Log::getInstance();
}
public function get($type, $id){
$this->log->Trace('ItemFactory::get');
if($id==NULL) $item = $this->getNew($type, $id);
else{
$cache=new Cache($type, $id);
if($cache->getTime() > 60*60){
$item = $this->Load($type, $id);
}else{
$item=$cache->get();
$item->WakeUpFromCache();
}
}
return $item;
}
private function Load($type, $id){
$this->log->Trace('ItemFactory::Load');
$item = $this->getNew($type, $id);
$item->Load();
return $item;
}
private function getNew($type, $id){
$this->log->Trace('ItemFactory::getNew');
$this->log->Trace($type);
return new $type($id);
}
}
?>
Et voilà un petit exemple
<?php
$factory = new ItemFactory();
//je charge un user depuis ma db ou le cache
$user = $factory->get('User', $my_id);
echo $user->getName();
//je veux crer un nouveau message
$message = $factory->get('Message', NULL);
$message->setUser($user);
$message->setTime(time());
$message->setContent('My message');
$message->Save();
?>
Qu'en pensez vous ?