GithubHelp home page GithubHelp logo

cart's Introduction

Cart

This is a very simple PHP cart library. Cart data can either be saved in PHP session or browser cookie.

Usage

Configuration

$cart= new Cart( [array $options] );

Options
Parameter Type Description
cartMaxItem int The maximum item can be added to cart. 0 = Unlimited
itemMaxQuantity int The maximum quantity per item can be added to cart. 0 = Unlimited
useCookie bool Use cookie to keep cart data when browser is closed.
// Include core Cart library
require_once 'class.Cart.php';

// Initialize Cart object
$cart = new Cart([
  // Can add unlimited number of item to cart
  'cartMaxItem'      => 0,
  
  // Set maximum quantity allowed per item to 99
  'itemMaxQuantity'  => 99,
  
  // Do not use cookie, cart data will lost when browser is closed
  'useCookie'        => false,
]);

Add Item

Adds an item to cart.

bool $cart->add( string $id[, int $quantity][, array $attributes] );

// Add item with ID #1001
$cart->add('1001');

// Add 5 item with ID #1002
$cart->add('1002', 5);

// Add item with ID #1003 with price, color, and size
$cart->add('1003', 1, [
  'price'  => '5.99',
  'color'  => 'White',
  'size'   => 'XS',
]);

// Item with same ID but different attributes will added as separate item in cart
$cart->add('1003', 1, [
  'price'  => '5.99',
  'color'  => 'Red',
  'size'   => 'M',
]);

Update Item

Updates quantity of an item. Attributes must be provides if item with same ID exists with different attributes.

bool $cart->update( string $id, int $quantity[, array $attributes] );

// Set quantity for item #1001 to 5
$cart->update('1001', 5);

// Set quantity for item #1003 to 2
$cart->update('1003', 2, [
  'price'  => '5.99',
  'color'  => 'Red',
  'size'   => 'M',
]);

Remove Item

Removes an item. Attributes must be provided to remove specified item, or all items with same ID will be removed from cart.

bool $cart->remove( string $id[, array $attributes] );

// Remove item #1001
$cart->remove('1001');

// Remove item #1003 with color White and size XS
$cart->remove('1003', [
  'price'  => '5.99',
  'color'  => 'White',
  'size'   => 'XS',
]);

Get Items

Gets a multi-dimensional array of items stored in cart.

array $cart->getItems( );

// Get all items in the cart
$allItems = $cart->getItems();

foreach ($allItems as $items) {
  foreach ($items as $item) {
    echo 'ID: '.$item['id'].'<br />';
    echo 'Qty: '.$item['quantity'].'<br />';
    echo 'Price: '.$item['attributes']['price'].'<br />';
    echo 'Size: '.$item['attributes']['size'].'<br />';
    echo 'Color: '.$item['attributes']['color'].'<br />';
  }
}

Get Item

Gets a multi-dimensional array of one item stored in cart.

array $cart->getItem( string $id[, string $hash] );

// Get first one item from the cart with id 1001
$theItem = $cart->getItem('1001');

// Get one item from the cart with any id and hash
$theItem = $cart->getItem($item['id'], $item['hash']);

Check Cart Empty

Checks if the cart is empty.

bool $cart->isEmpty( );

if ($cart->isEmpty()) {
  echo 'There is nothing in the basket.';
}

Get Total Item

Gets the total of items in the cart.

int $cart->getTotaltem( );

echo 'There are '.$cart->getTotalItem().' items in the cart.';

Get Total Quantity

Gets the total of quantity in the cart.

int $cart->getTotalQuantity( );

echo $cart->getTotalQuantity();

Get Attribute Total

Gets the sum of a specific attribute.

int $cart->getAttributeTotal( string $attribute );

echo '<h3>Total Price: $'.number_format($cart->getAttributeTotal('price'), 2, '.', ',').'</h3>';

Clear Cart

Clears all items in the cart.

$cart->clear( );

$cart->clear();

Destroy Cart

Destroys the entire cart session.

$cart->destroy( );

$cart->destroy();

Item Exists

Checks if an item exists in cart.

bool $cart->isItemExists( string $id[, array $attributes] );

if ($cart->isItemExists('1001')) {
  echo 'This item already added to cart.';
}

cart's People

Contributors

atanasov avatar bigmanatee avatar josxha avatar seikan avatar yllumi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cart's Issues

Update Cart Doesn't work

I don't think the update cart function is working. I tried on the example.php file you provided. it doesn't really work

GREAT CART

Only small remark ///
This is not working - itemMaxQuantity' => 99, // 0 = Unlimited
When set to 0 - it is really zero.

Update all Items

Hi, I have a button for update but how can I update all items not just one?

// Update item
if (isset($_POST['update'])) {

	$cart->update($_POST['id'], $_POST['qty'], [
		'price' => $_POST['price'],
		'color' => (isset($_POST['color'])) ? $_POST['color'] : '',
		'size' => (isset($_POST['size'])) ? $_POST['size'] : '',
	]);
}

Change color

Hi what happen if I add two products with the color red, and other with white color both dame id but then I want to change one to a blue color how that work with this class?

Why Double Array?

I'm finding your cart very interesting, i wondered why the product are inside a double array?
I'm curious to kown the reason. Thank You Very Much!

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [quantity] => 1
                    [hash] => 82aa6954b3eecf592b1e8fb86063fd80
                    [attributes] => Array
                        (
                            [price] => 349
                            [color] => Silver
                        )

                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [quantity] => 1
                    [hash] => a4da6514bfe02e8b9ad747387005561a
                    [attributes] => Array
                        (
                            [price] => 449
                            [color] => Silver
                            [size] => Small
                        )

                )

        )

)

can't update quantity of the cart

Hello,

i cant update the quantity of my cart.
here is my code:

`
if($_GET['do'] == "change")
{
$quantity = $_POST['quantity'];
$id = $_GET['id'];

		$cart->update($id, $quantity);
		
		header('location: cart.php');
		exit;
	}

`

Error with cart update after removal of first item in product group

First of all, thanks for the class, it works great. However, I found a small bug while using product variants. If you add two or more variants of the same product to the cart, and removes the one with index 0, the indexing goes bad. This is because, the array doesn't get re-indexed after item removal, and each cart operation starts at index 0. I found that re-indexing the variant arrays after the removal of a variant fixes this.

public function remove($id, $attributes = []){
...
unset($this->items[$id][$index]);
$this->items[$id] = array_values($this->items[$id]);
...
}

Item not always removing

Hi using your example, I have found that an item sometimes 1 item does not get removed. tried to add 3 items of the same id with different colors, and removing although get this error:

2018-05-13_22-48-53

However sometimes there is no error and just doesnt allow me to delete the rest of the items. See if you're able to reproduce this error, by just adding different colors of the same product. then deleting one by one, you'll see that for some reason one of them wont delete

Post without refreshing

hey any chance you can provide me an example of this working through using a database for the data?

Cart ID - Undefined index ID

I am trying to use this class to implement into my shopping cart and according to the examples i am creating entries in my cart and i am trying to use a non-numeric value as 'id' and then later call it in my cart

  $cart->add('hash123',1, [
    'image' =>'some-jpg-123.jpg'
  ]);
// later 
foreach(c::get('cart')->getItems() as $items):
foreach($items as $cart):
<a href="/thumbs/<?php echo byHash($cart['id']) ?>/<?php echo $cart['attributes']['image'] ?>">....</a>
endforeach;
endforeach;

when outputting the raw data, it doesn't have any sort of "id" index... output is for example:

Array
(
    [1lgw886] => Array
        (
            [0] => Array
                (
                    [quantity] => 1
                    [hash] => 8fdd062086410a3f8cc5552c3c4f9363
                    [attributes] => Array
                        (
                            [image] => studio-black-2017-18-41-00.jpg
                        )

                )

        )

)

multiple carts - favorites

I'd love to see this cart solution twice in use: One for a classic cart. And another "cart" as a favorite list to tag products that you want to buy later or products you want to compare.

Max Quantity Cart Question

I have a project that this could be amazing with but was wondering how we would implement the following:

  • We would like to limit purchases to 1 item per 28 days (this should be easy enough)

Ultimately we would also like to set limits based on supplier or category (whichever is easier)

  • This limit only applies to a specific supplier (Say Supplier ID: 1) and supplier ID: 2 wouldn't have any limitation
    or
  • This limit only applies to particular categories (I.E. Laptops, Tablets, Monitors)

Whichever way is easier to implement..

Any assistance would be great :) thank you in advance.

Update error

Hello,
i have try to add update of product not quantity but attribute
I use Ajax

$poscart->update(5, 2, [ 'price' => 8.00,'name'=>'New name']);

but not work ... where I make error ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.