Created
April 22, 2020 16:42
-
-
Save khatabwedaa/bd311f0327f6875d8d195a1c7935f1d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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