Skip to content

Instantly share code, notes, and snippets.

@mandado
Last active December 19, 2015 01:38
Show Gist options
  • Save mandado/5877026 to your computer and use it in GitHub Desktop.
Save mandado/5877026 to your computer and use it in GitHub Desktop.
Class of shopping Cart for studies
<?php
require './KeyNotFoundException.php';
class Cart{
protected $item;
public function __construct() {
$this->item = [];
}
public function addItem($idItem, array $itemsOptions = array()) {
$this->item[$idItem] = $itemsOptions;
}
public function updateItem($idItem, array $arrayOptionsToUpdate = array()) {
foreach ($arrayOptionsToUpdate as $key => $value) {
$this->item[$idItem][$key] = $value;
}
}
public function removeItem($idItem){
unset($this->item[$idItem]);
}
public function getItem($id) {
return (isset($this->item[$id]) ? $this->item[$id] : $this->fireException('KeyNotFoundException'));
}
public function getItems() {
return $this->item;
}
public function getItemsFormattedArray(){
var_dump($this->item);
}
private function fireException($exception) {
switch ($exception) {
case 'KeyNotFoundException':
throw new KeyNotFoundException('Não existe este item no array', 1);
break;
}
}
}
?>
<?php
class KeyNotFoundException extends Exception {
public function __construct($message, $code) {
parent::__construct($message, $code);
}
/* Representação do objeto personalizada no formato string */
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment