La POO fait un tel "buzz" en ce moment que j'ai décidé de m'y mettre. Le soucis c'est que j'aimerais bien savoir si ce que j'ai déjà fait est (vraiment) correct.
C'est un (banal) système de panier, composé de 3 classes. Une construite en Singleton pour gérer les sessions, une autre qui gère le "catalogue" et enfin la dernière pour gérer le panier.
Si vous pouviez me dire ce que vous en pensez (et surtout comment corriger et améliorer) ça serait très gentil.
La classe Sessions (Singleton)
Code : Tout sélectionner
class Sessions
{
private static $instance = null;
private $cart;
private function __construct()
{
session_start();
}
public static function getInstance()
{
if (is_null(self::$instance))
self::$instance = new Sessions();
else
return self::$instance;
}
public function initCart()
{
if (!isset($_SESSION['cart']))
return $this->cart = array();
else
return $this->cart = unserialize($_SESSION['cart']);
}
public function setCart($items)
{
$_SESSION['cart'] = serialize($items);
}
public function __clone()
{
}
public function __destruct()
{
}
}
Code : Tout sélectionner
class Store
{
protected $db;
private $product;
public function __construct()
{
if (is_readable(PRODUCTS_DB))
$this->db = new SimpleXMLElement(file_get_contents(PRODUCTS_DB));
else
return exit('Products xml database missing or unreadable.');
}
private function productSelect($id)
{
return $this->db->Xpath('/products/product[id="'.$id.'"]');
}
protected function productExist($id)
{
if (count($this->productSelect($id)) > 0)
return true;
else
return false;
}
public function productPrice($id)
{
if ($this->productExist($id))
$this->product = $this->productSelect($id);
return $this->product[0]->price;
}
public function productName($id)
{
if ($this->productExist($id))
$this->product = $this->productSelect($id);
return $this->product[0]->name;
}
public function viewStore()
{
return $this->db->product;
}
}
Code : Tout sélectionner
class Cart extends Store
{
protected $items;
private $total;
public function __construct()
{
parent::__construct();
$this->items = Sessions::getInstance();
$this->items = Sessions::initCart();
}
public function addItem($id)
{
if (array_key_exists($id, $this->items))
$this->items[$id]++;
else
$this->items[$id] = 1;
}
public function delItem($id)
{
if (array_key_exists($id, $this->items))
if ($this->items[$id] > 1)
$this->items[$id]--;
else
unset($this->items[$id]);
}
public function emptyCart()
{
$this->items = array();
}
public function nbItems()
{
return array_sum($this->items);
}
public function viewCart()
{
return $this->items;
}
public function totalCart()
{
$this->total = 0;
foreach ($this->items as $id => $qty)
{
$this->total += parent::productPrice($id) * $qty;
}
return $this->total;
}
public function __destruct()
{
Sessions::getInstance()->setCart($this->items);
}
}Voilà, j'attends avec impatience vos commentaires
Merci !