• This repository has been archived on 29/Mar/2020
  • Stars
    star
    143
  • Rank 257,007 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 13 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A flexible and modern shopping cart

โš ๏ธ This project is no longer maintained

Cart

Packagist Build Status Scrutinizer Quality Score SensioLabs Insight Code Coverage Total Downloads License

A flexible and modern shopping cart package.

Prerequisites

  • PHP >=5.6.0

Installation

composer require mike182uk/cart

Usage

Cart

Create a new cart

To create a new cart instance you must pass an id and a storage implementation to the cart constructor:

use Cart\Cart;
use Cart\Storage\SessionStore;

$id = 'cart-01';
$cartSessionStore = new SessionStore();

$cart = new Cart($id, $cartSessionStore);

The storage implementation must implement Cart\Storage\Store.

The id is used for saving / restoring cart state via the storage implementation.

Add an item to the cart

Use the add method to add an item to the cart. A valid Cart\CartItem must be passed to this method.

use Cart\CartItem;

$item = new CartItem;
$item->name = 'Macbook Pro';
$item->sku = 'MBP8GB';
$item->price = 1200;
$item->tax = 200;

$cart->add($item);

If the item already exists in the cart, the quantity of the existing item will be updated to include the quantity of the item being added.

Remove an item from the cart

Remove an item from the cart by passing the item id to the remove method.

$cart->remove('e4df90d236966195b49b0f01f5ce360a356bc76b');

Update an item in the cart

To update a property of an item in the cart use the update method. You will need to pass the cart item id, the name of the property to update and the new value. This method will return the item id (in case it has changed due to the update).

$newId = $cart->update('e4df90d236966195b49b0f01f5ce360a356bc76b', 'price', 959.99);

If you try and update an item that does not exist in the cart a InvalidArgumentException will be thrown.

Retrieve an item in the cart

Retrieve an item from the cart by its id use the get method. If the item does not exist null is returned.

$item = $cart->get('e4df90d236966195b49b0f01f5ce360a356bc76b');

if ($item) {
    // ...
}

Retrieve all items in the cart

Retrieve all items in the cart using the all method. This will return an array of all the items in the cart.

$cartItems = $cart->all();

if (count($cartItems) > 0) {
    foreach ($cartItems as $item) {
        // ...
    }
}

Determine if an item exists in the cart

Determine if an item exists in the cart using the has method. Returns true or false.

if ($cart->has('e4df90d236966195b49b0f01f5ce360a356bc76b')) {
    // ...
}

Clear The Cart

Clear the cart using the clear method.

$cart->clear();

This will also clear the saved state for this cart in the store.

Save / restore cart state

Save the cart using the save method.

$cart->save();

This will save the current cart items and cart id to the store.

Restore the cart using the restore method.

$cart->restore();

This will add any stored cart items back to the cart and set the cart id. If there is a problem restoring the cart a Cart\CartRestoreException will be thrown. This will only happen if:

  • the saved data is unserializable
  • the unserialized data is invalid (not an array)
  • the cart id is not present in the unserialized data
  • the cart items are not present in the unserialized data
  • the cart id is invalid (not a string)
  • the cart items are invalid (not an array)

Other Cart Methods

totalUniqueItems

Get the total number of unique items in the cart.

$cart->totalUniqueItems();
totalItems

Get the total number of items in the cart.

$cart->totalItems();
total

Get the total price of all the cart items including tax.

$cart->total();

You can get the total excluding tax by using the totalExcludingTax method.

$cart->totalExcludingTax();
tax

Get the total tax of all the cart items.

$cart->tax();
toArray

Export the cart to an array.

$cartData = $cart->toArray();

Array will be structured like:

[
    'id' => 'cart-01', // cart id
    'items' => [
        // cart items as array
    ]
]
getId

Get the id of the cart.

$cart->getId();
getStore

Get the cart storage implementation.

$cart->getStore();

Cart Item

Create a new Cart Item

use Cart\CartItem;

$item = new CartItem;

$item->name = 'Macbook Pro';
$item->sku = 'MBP8GB';
$item->price = 1200;
$item->tax = 200;
$item->options = [
    'ram' => '8 GB',
    'ssd' => '256 GB'
];

Cart\CartItem implements ArrayAccess so properties can be assigned to the cart item as if accessing an array:

$item = new CartItem;

$item['name'] = 'Macbook Pro';
$item['sku'] = 'MBP8GB';
$item['price'] = 1200;
$item['tax'] = 200;
$item['options'] = [
    'ram' => '8 GB',
    'ssd' => '256 GB'
];

An array of data can also be passed to the cart item constructor to set the cart item properties:

$itemData = [
    'name' => 'Macbook Pro';
    'sku' => 'MBP8GB';
    'price' => 1200;
    'tax' => 200;
    'options' => [
        'ram' => '8 GB',
        'ssd' => '256 GB'
    ]
];

$item = new CartItem($itemData);

If no quantity is passed to the cart item constructor, the quantity is set to 1 by default.

If no price is passed to the cart item constructor, the price is set to 0.00 by default.

If no tax is passed to the cart item constructor, the tax is set to 0.00 by default.

Cart Item ID

Each cart has a unique ID. This ID is generated using the properties set on the cart item. You can get the cart item ID using the method getId or by accessing the property id.

$id = $item->getId();
$id = $item->id;
$id = $item['id'];

Changing a property on the cart item will change its ID.

Cart Item Methods

get

Get a piece of data set on the cart item.

$name = $item->get('name');

This is the same as doing:

$name = $item['name'];
$name = $item->name;

set

Set a piece of data on the cart item.

$item->set('name', 'Macbook Pro');

This is the same as doing:

$item['name'] = 'Macbook Pro';
$item->name = 'Macbook Pro';

If you are setting the item quantity, the value must be an integer otherwise an InvalidArgumentException is thrown.

$item->quantity = 1; // ok

$item->quantity = '1' // will throw exception

If you are setting the item price or tax, the value must be numeric otherwise an InvalidArgumentException is thrown.

$item->price = 10.00; // ok

$item->price = '10' // ok

$item->price = 'ten' // will throw exception
getTotalPrice

Get the total price of the cart item including tax ((item price + item tax) * quantity).

$item->getTotalPrice();

You can also get the total price excluding tax (item price * quantity) using the getTotalPriceExcludingTax method.

$item->getTotalPriceExcludingTax();
getSinglePrice

Get the single price of the cart item including tax (item price + item tax)

$item->getSinglePrice();

You can also get the single price excluding tax by using the getSinglePriceExcludingTax method.

$item->getSinglePriceExcludingTax();
getTotalTax

Get the total tax of the cart item (item tax * quantity).

$item->getTotalTax();
getSingleTax

Get the single tax value of the cart item.

$item->getSingleTax();
toArray

Export the item to an array.

$itemArr = $item->toArray();

Array will be structured like:

[
    'id' => 'e4df90d236966195b49b0f01f5ce360a356bc76b', // cart item unique id
    'data' => [
        'name' => 'Macbook Pro',
        'sku' => 'MBP8GB',
        'price' => 1200,

        // ... other cart item properties
    ]
]

Cart Storage Implementation

A cart storage implementation must implement Cart\Storage\Store.

This package provides 2 basic storage implementations: Cart\Storage\SessionStore and Cart\Storage\CookieStore.

When the save method of the cart is called, the cart id and serialized cart data is passed to the put method of the storage implementation.

When the restore method of the cart is called, the cart id is passed to the get method of the storage implementation.

When the clear method of the cart is called, the cart id is passed to the flush method of the storage implementation.

An example session storage implementation may look like:

use Cart\Store;

class SessionStore implements Store
{
    /**
     * {@inheritdoc}
     */
    public function get($cartId)
    {
        return isset($_SESSION[$cartId]) ? $_SESSION[$cartId] : serialize([]);
    }

    /**
     * {@inheritdoc}
     */
    public function put($cartId, $data)
    {
        $_SESSION[$cartId] = $data;
    }

    /**
     * {@inheritdoc}
     */
    public function flush($cartId)
    {
        unset($_SESSION[$cartId]);
    }
}

More Repositories

1

paypal-ipn-listener

A PayPal IPN (Instant Payment Notification) listener for PHP
PHP
89
star
2

timestring

Parse a human readable time string into a time based value
JavaScript
70
star
3

snpt

A gist powered CLI snippet retriever
Go
21
star
4

magento-dev-vagrant-chef-solo

Development box configured to run Magento CE.
Ruby
10
star
5

homebridge-zwave

A Homebridge plugin for ZWave devices
JavaScript
10
star
6

browser-sync-reuse-tab

Attempt to reuse an existing tab that was opened by BrowserSync
JavaScript
9
star
7

lamp-vagrant-chef-solo

LAMP development box with Vagrant and Chef Solo
Ruby
8
star
8

cellref

Convert between cell reference styles (A1 notation & R1C1 notation)
JavaScript
7
star
9

alfred-snpt

An Alfred workflow for snpt
Makefile
6
star
10

fetch-gists

Fetch all of your gists from GitHub
JavaScript
5
star
11

alfred-switch-audio

An Alfred workflow for setting the input / output audio device
Shell
5
star
12

playlist-pipeline

๐ŸŽต A CLI for programmatically organising, pruning & grooming your Spotify playlists
JavaScript
5
star
13

packer-lamp-vagrant-base-box

Packer project for building a LAMP development base box for use with vagrant
Shell
3
star
14

dotfiles

๐Ÿก
Shell
3
star
15

homebrew-tap

๐Ÿบ Homebrew formulae & casks for various tools
Ruby
2
star
16

phpspec-run-fqcn

Run a spec for a class using its FQCN
PHP
2
star
17

findmeafireteam

๐Ÿง™โ€โ™‚๏ธJust another Destiny LFG site
JavaScript
2
star
18

tmpdl

Download a remote file to a temporary location
JavaScript
2
star
19

CoffeeWriter

โ˜• A simple desktop app for quickly compiling CoffeeScript (macOS)
JavaScript
2
star
20

mdb.sh

๐Ÿ‘จ๐Ÿผโ€๐Ÿ’ป My personal website
TypeScript
1
star
21

puppet-phpcsfixer

Puppet module for PHP CS Fixer
Puppet
1
star
22

xbl-friends

๐ŸŽฎ A menu bar application to see when your Xbox live friends are online
JavaScript
1
star
23

code-katas

My attempts at various Code Katas
Go
1
star
24

phpspec-rename

Use PHPSpec to rename a class and its corresponding spec
PHP
1
star
25

kata

PHP
1
star
26

snake

๐Ÿ A simple JavaScript implementation of Snake
JavaScript
1
star
27

nodespec

A tool to help drive emergent design by specification in Node.JS
JavaScript
1
star
28

project-euler

My solutions to Project Euler problems
Go
1
star