A reusable shopping cart implementation.
composer require mrprompt/shopping-cart
You can initializes a cart passing an array of items. An item is a instance of Item
class
or an implementation of ItemInterface
.
use \MrPrompt\ShoppingCart\Cart;
use \MrPrompt\ShoppingCart\Item;
$items = [
new Item(uniqid()),
new Item(uniqid(), 1.00),
new Item(uniqid(), 5.00, 10),
];
$cartId = uniqid();
$cart = new Cart($cartId, $items);
You can add items to an existent cart passing an instance of Item
.
use \MrPrompt\ShoppingCart\Item;
$itemId = uniqid();
$itemPrice = 1.99;
$itemQuantity = 30;
$item = new Item($itemId, $itemPrice, $itemQuantity);
$cartId = uniqid();
$cart = new Cart($cartId);
$cart->addItem($item);
Pass an instance of Item
- previously added to cart obvously - to remove it.
use \MrPrompt\ShoppingCart\Item;
$itemId = uniqid();
$itemPrice = 1.99;
$itemQuantity = 30;
$item = new Item($itemId, $itemPrice, $itemQuantity);
$cartId = uniqid();
$cart = new Cart([ $item ]);
$cart->removeItem($item);
To remove all items from cart, you can use the cleanUp
method:
use \MrPrompt\ShoppingCart\Cart;
use \MrPrompt\ShoppingCart\Item;
$itemId = uniqid();
$itemPrice = 1.99;
$itemQuantity = 30;
$item = new Item($itemId, $itemPrice, $itemQuantity);
$cartId = uniqid();
$cart = new Cart($cartId, [ $item ]);
echo $cart->count(); // === 1
$cart->cleanUp();
echo $cart->count(); // === 0
To check if the cart is empty, you can use isEmpty
method:
use \MrPrompt\ShoppingCart\Cart;
use \MrPrompt\ShoppingCart\Item;
$itemId = uniqid();
$itemPrice = 1.99;
$itemQuantity = 30;
$item = new Item($itemId, $itemPrice, $itemQuantity);
$cartId = uniqid();
$cart = new Cart($cartId, [ $item ]);
echo $cart->isEmpty(); // === false
$cart->cleanUp();
echo $cart->isEmpty(); // === true
phpunit --coverage-text --testdox