lombervid/shoppingcart

A simple shopping cart class for PHP

v3.0.0 2023-06-01 00:31 UTC

This package is auto-updated.

Last update: 2024-09-15 01:50:56 UTC


README

GitHub release (latest SemVer) Packagist PHP Version tests GitHub

ShoppingCart PHP Class

ShoppingCart is a simple PHP package that provides you with a simple shopping cart implementation stored in session.

Installation

Composer

You can install it using composer:

composer require lombervid/shoppingcart

Usage

Create an instance of ShoppingCart class.

use Lombervid\ShoppingCart\ShoppingCart;

$shoppingCart = new ShoppingCart();

Add items

You can add items calling the method add() passing an Item instance as parameter.

use Lombervid\ShoppingCart\Item;
use Lombervid\ShoppingCart\ShoppingCart;

$cart = new ShoppingCart();
$cart->add(new Item('1', 'Cake', 15.56));
$cart->add(new Item('15', 'Frappe', 5));

foreach ($cart->items() as $item) {
	// $item->id
	// $item->name
}

at this point your $cart->items() will look like this:

array:2 [▼
  1 => Lombervid\ShoppingCart\Item {#5 ▼
    -id: "1"
    -name: "Cake"
    -price: 15.56
  }
  15 => Lombervid\ShoppingCart\Item {#6 ▼
    -id: "15"
    -name: "Frappe"
    -price: 5.0
  }
]

Add extra fields to your item

You can also add extra fields (such as price, name, etc) to your item. The Item constructor receives a parameter fields which is an Array with the following structure:

[
    'field_name'   => 'field_value',
    'field_2_name' => 'field_2_value'
]

when you provide the $fields param, each field of the array is added to your item.

$fields = [
	'size'  => 'XL',
	'color' => 'blue'
];

$item = new Item('23', 'My Shirt', 2.5, fields: $fields);
$cart->add($item);

with the above code your $cart->items() will look line:

array:1 [▼
  23 => Lombervid\ShoppingCart\Item {#5 ▼
    -id: "23"
    -name: "My Shirt"
    -price: 2.5
    -qty: 1
    -fields: array:2 [▼
      "size" => "XL"
      "color" => "blue"
    ]
  }
]

Then you can access any extra field as if they were properties:

foreach ($cart->items() as $item) {
    // $item->size
    // $item->color
}

Remove items

You can remove an item from the cart calling the method remove($id) which receive item's $id as parameter.

$cart->remove(23);

Clear the cart

You can clear the cart calling the method clear() which removes all the items from the cart.

$shoppingCart->clear();

Advanced options

ShoppingCart

Cart options

It is an array of options. The default value is:

[
    'name'     => 'shopping_cart',
    'autosave' => true,
    'tax'      => 0,
    'shipping' => [
        'amount' => 0,
        'free'   => 0,
    ],
]

Constructor

Methods

Item

Constructor

Methods

Contributing

Refer to CONTRIBUTING for information.

License

MIT