Hallo,
Ik heb een shoppingcart class in elkaar gezet:
<?php
class Cart implements JsonSerializable {
private $cartItems;
public function __construct($cartItems = array()) {
$this->cartItems = $cartItems;
}
public function addItem(CartItem $cartItem) {
$this->cartItems[] = $cartItem;
}
public function getItemByIndex($index) {
return isset($this->cartItems[$index]) ? $this->cartItems[$index] : null;
}
public function getItemsByProductId($productId) {
$items = array();
foreach ($this->cartItems as $item) {
if ($item->getId() === $productId) {
$items[] = $item;
}
}
return $items;
}
public function getItems() {
return $this->cartItems;
}
public function setItem($index, $cartItem) {
if (isset($this->cartItems[$index])) {
$this->cartItems[$index] = $cartItem;
}
return $this;
}
public function removeItem($index) {
unset($this->cartItems[$index]);
return $this;
}
public function jsonSerialize() {
$items = array();
foreach ($this->cartItems as $item) {
$items[] = array(
'id' => $item->getId(),
'quantity' => $item->getQuantity(),
'note' => $item->getNote());
}
return $items;
}
}
class CartItem {
private $id;
private $quantity;
private $note;
public function __construct($id, $quantity = 0, $note = null) {
$this->id = $id;
$this->quantity = $quantity;
$this->note = $note;
}
public function getId() {
return $this->id;
}
public function getQuantity() {
return $this->quantity;
}
public function getNote() {
return $this->note;
}
public function setId($id) {
$this->id = $id;
return $this;
}
public function setQuantity($quantity) {
$this->quantity = $quantity;
return $this;
}
public function setNote($note) {
$this->note = $note;
return $this;
}
}
?>
De functies werken wel prima. Bijvoorbeeld als ik $item = $cart->setItem(1,1,'test'); doe voeg ik een product toe in de $cartItems array. Maar nu komt het lastige (in mijn mening). Ik heb een product pagina met één knop. Die knop moet een product met de desbetreffende code kunnen toevoegen in een cookie, mocht het product al bestaan dan zou het met de code de quantity moeten kunnen aanpassen. Ik loop dus best wel erg vast bij het opslaan van een product in een cookie. Zodra ik $item = $cart->addItem(); doe en dan vervolgens de cookie aanmaak met behulp van het cart object. dan krijg ik alleen het laatst toegevoegde product te zien, en niet de vorige geadde producten.
3.514 views