I built a small store site for learning purposes. I loaded my 'products' from the db into a Products
class. I used a method from this class to display the products in HTML. Of course, the HTML contains 'Add to Cart' buttons which POST the product ID and quantity when a button is clicked. The result is that the POSTed ID and quantity are sent to the Cart
class. This works, but it seems like I should be sending a product object to my cart instead of just two values that will be stored in an array.
I'm not sure how to do that, given that product information needs to be POSTed non-objectively. And I'm not sure if it would be better.
class Products
{
private $products;
function __construct($data)
{
$this->products = $data;
}
public function showProduct($id, $price, $type)
{
echo "<div id='$id' class='product'>";
echo $type."<br/>";
echo $price."<br/>";
echo "Quantity: <input class='quantity' name='quantity' value='1' type='text'/><br/>";
echo "<button onclick='add($id);'>Add to Cart</button>";
echo "</div>";
}
public function showAll()
{
foreach ($this->products as $id => $product) {
$this->showProduct($id, $product->price, $product->type);
}
}
}
And the Cart
class:
class Cart
{
public $items = array();
function __construct() {
if (isset($_SESSION['cart'])) { $this->items = $_SESSION['cart']; } else { $_SESSION['cart'] = ''; }
}
private function update() {
$_SESSION['cart'] = $this->items;
}
public function add($id, $quantity) {
$this->items[] = array('id'=>"$id", 'quantity'=>"$quantity");
$this->update();
}
}
I'm not sure that I was able to get the objects from these classes to interact with each other properly.
Also, in this situation, since I need to use $_SESSION
to keep the cart inventory persistent, I'm not sure why I need a Cart
class at all. It seems a little superfluous, but I have a nagging feeling that it shouldn't be.