rogervila / cart
PHP Shopping cart using Fowler's Money pattern
Installs: 9
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 3
Open Issues: 1
pkg:composer/rogervila/cart
Requires
- php: ^5.6 || ^7.0
- florianv/swap: ^3.0
- moneyphp/money: ^3.0
- php-http/guzzle6-adapter: ^1.1
Requires (Dev)
- phpunit/phpunit: ^5.7
This package is auto-updated.
Last update: 2025-10-04 19:46:20 UTC
README
DO NOT USE IT ON PRODUCTION BEFORE 1.0.0 IS TAGGED
Cart is based on sessions, and follows the Fowler's Money pattern.
Main features.
- 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
Create a Cart
The cart constructor accepts an ID
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
$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
Add a currency
By default, Cart will work with float numbers if a currency is not set
In order to add a currency, just add this
$cart = new Cart(); $cart->currency('EUR'); // add an ISO4217 currency
Create Items
When an Item is created, it must receive a unique ID
use Cart\Item; $item = new Item('mandatoryUniqueId');
Add Item data
Instead of passing only the ID, an array with data can be passed.
$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
$fields = [ 'foo' => 'bar' ] $item->fields($fields);
When the item price is set with an integer, it will be parsed as cents, so
(int) 999will be parsed as(string) '9.99'
Also, Item data can be added with fluent
$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
$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
var_dump($cart->subtotal());
Add Fees
Fees can have a percentage or a fixed value
TODO
Add Conditions
TODO
Get total
Gets the final result, after applying Item conditions, Cart conditions and Fees
TODO
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