ksdev/shopping-cart

0.2.6 2015-08-05 18:28 UTC

This package is not auto-updated.

Last update: 2024-04-27 16:14:17 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score

Original source: http://www.peachpit.com/articles/article.aspx?p=1962481 by Larry Ullman. See the article for description and compare source code for changes.

Install

Via Composer

$ composer require ksdev/shopping-cart

Usage

use Ksdev\ShoppingCart\Cart;
use Ksdev\ShoppingCart\Currency;
use Ksdev\ShoppingCart\Item;

$cart = new Cart(new Currency('PLN'));

$tax = '23.00';                                 // Tax is optional

$item1 = new Item('SKU1', 'Item 1', '100.00', $tax);
$item2 = new Item('SKU2', 'Item 2', '200.00', $tax);
$item3 = new Item('SKU3', 'Item 3', '300.00', $tax);

$cart->addItem($item1);
$cart->addItem($item2);
$cart->addItem($item3);

if (!$cart->isEmpty()) {
    foreach ($cart as $arr) {
        $item = $arr['item'];
        var_dump($item->getSku());              // E.g. string(4) "SKU1"
        var_dump($item->getName());             // E.g. string(6) "Item 1"
        var_dump($item->getPrice());            // E.g. string(6) "100.00"
        var_dump($item->getTax());              // E.g. string(5) "23.00"
        var_dump($arr['qty']);                  // E.g. int(1)
    }
}

var_dump($cart->total());                       // string(6) "600.00"
var_dump($cart->getCurrency()->getCode());      // string(3) "PLN"

$item4 = new Item('SKU1', 'Item 1', '100.00', $tax);  // Same as $item1
$cart->addItem($item4);

var_dump($cart->total());                       // string(6) "700.00"
var_dump($cart->count());                       // int(4); also: count($cart)
var_dump($cart->countUnique());                 // int(3)

$cart->updateItem($item2, 3);                   // 3 is the new quantity

var_dump($cart->count());                       // int(6)
var_dump($cart->countUnique());                 // int(3)

$cart->updateItem($item2, 0);                   // Removes the item from the cart

var_dump($cart->count());                       // int(3)
var_dump($cart->countUnique());                 // int(2)

$cart->deleteItem($item1);                      // Removes the item from the cart

var_dump($cart->count());                       // int(1)
var_dump($cart->countUnique());                 // int(1)

var_dump($cart->getItem('SKU3'));               // Get item by Stock Keeping Unit
/*
    array(2) {
        'item' => class Ksdev\ShoppingCart\Item#270 (3) {
            protected $sku   => string(4) "SKU3"
            protected $name  => string(6) "Item 3"
            protected $price => string(6) "300.00"
            protected $tax   => string(5) "23.00"
        }
        'qty' => int(1)
    }
*/

Testing

$ composer test

Credits

  • Larry Ullman

License

The MIT License (MIT). Please see License File for more information.