Skip to content

Instantly share code, notes, and snippets.

@khatabwedaa
Created April 22, 2020 16:42
Show Gist options
  • Save khatabwedaa/bd311f0327f6875d8d195a1c7935f1d5 to your computer and use it in GitHub Desktop.
Save khatabwedaa/bd311f0327f6875d8d195a1c7935f1d5 to your computer and use it in GitHub Desktop.
<?php
namespace App;
class Cart
{
private $cart;
public function __construct()
{
if ($this->get() === null)
$this->set([]);
$this->cart = $this->get();
}
public function add(Product $product): void
{
$item = [
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'quantity' => 1,
];
if (!$this->exists($item)) {
array_push($this->cart, $item);
}
$this->set($this->cart);
}
public function remove(int $productId): void
{
array_splice($this->cart, array_search($productId, array_column($this->cart, 'id')), 1);
$this->set($this->cart);
}
public function clear(): void
{
$this->set([]);
}
public function get(): ?array
{
return request()->session()->get('cart');
}
private function set($cart): void
{
request()->session()->put('cart', $cart);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment