Cart
DO NOT USE IT ON PRODUCTION BEFORE 1.0.0 IS TAGGED, (*1)
, (*2)
Cart is based on sessions, and follows the Fowler's Money pattern., (*3)
Main features., (*4)
- Currency Management
- OOP
- Custom session/cache management
- Framework agnostic
- Easy integration
Install
$ composer require rogervila/cart
Setup
Cart has two basic objects: Cart and Item, (*5)
Create a Cart
The cart constructor accepts an ID, (*6)
use Cart\Cart;
$cart = new Cart(); // generates an automatic ID
// OR
$cart = new Cart('myCustomId');
Retrieve a Cart
If it exists, the Cart will be retrieved from the session by passing it's ID, (*7)
$cart = new Cart('myCustomId'); // If it exists on the session, retrieves it instead of creating a new one
Change the Cart ID
$cart = new Cart(); // generates an automatic ID
$cart->id('myCustomID'); // Changes the ID
When the cart id changes, the old session is not deleted, (*8)
Add a currency
By default, Cart will work with float numbers if a currency is not set, (*9)
In order to add a currency, just add this, (*10)
$cart = new Cart();
$cart->currency('EUR'); // add an ISO4217 currency
Create Items
When an Item is created, it must receive a unique ID, (*11)
use Cart\Item;
$item = new Item('mandatoryUniqueId');
Add Item data
Instead of passing only the ID, an array with data can be passed., (*12)
$item = new Item([
'id' => 'uniqueId',
'name' => 'Banana',
'quantity' => 1, // must be an integer
'price' => '0.99' // it accepts strings and integers
]);
Add Item custom data
In order to add custom fields, a fields() method is provided, (*13)
$fields = [
'foo' => 'bar'
]
$item->fields($fields);
When the item price is set with an integer, it will be parsed as cents, so (int) 999 will be parsed as (string) '9.99', (*14)
Also, Item data can be added with fluent, (*15)
$item = new Item(123);
$item->quantity(2)->price('0.99')->name('Banana');
Add Items to the cart
If the item does not have a quantity, it will be set to 1, (*16)
$items = [
new Item('id1'),
new Item('id2'),
]
$cart->add($items);
// OR
$cart->add($item1)->add($item2); // etc...
Get subtotal
Gets the sum from all Cart Items, (*17)
var_dump($cart->subtotal());
Add Fees
Fees can have a percentage or a fixed value, (*18)
TODO, (*19)
Add Conditions
TODO, (*20)
Get total
Gets the final result, after applying Item conditions, Cart conditions and Fees, (*21)
TODO, (*22)
Todos
- Full documentation
- Allow price conversion when the currency changes
- Choose between automatic and manual conversion
- Update the cart items currency when the Cart currency is changed
- Integrate Conditions (discounts, coupons, etc) with custom rules
- Add Fees (Taxes, Shipping, etc)
- More tests
License
MIT, (*23)