简体   繁体   中英

Shopping Cart using object oriented PHP

I have recently found some code online on an OO shopping cart. The results show as follows with items already in the cart.

Cart Contents (2 items)

Some Widget: 1 @ $23.45 each.

Another Widget: 4 @ $12.39 each.

My goal is to have something like below but with a product list that allows users to add/remove items themselves into a cart (like above) but using buttons and allowing the user to change the quantity themselves. Can anyone help me with how I could implement this? I've also heard about people using sessions in their cart? Any help is appreciated, thanks!

Product List

Some Widget: $23.45 each. Quantity (1) ADD TO CART

Another Widget: $12.39 each. Quantity (1) ADD TO CART

Cart

Another Widget: $12.39. Quantity (4) REMOVE

ShoppingCart.php

<?php
class ShoppingCart implements Iterator, Countable {

// Array stores the list of items in the cart:
protected $items = array();

// For tracking iterations:
protected $position = 0;

// For storing the IDs, as a convenience:
protected $ids = array();

// Constructor just sets the object up for usage:
function __construct() {
    $this->items = array();
    $this->ids = array();
}

// Returns a Boolean indicating if the cart is empty:
public function isEmpty() {
    return (empty($this->items));
}

// Adds a new item to the cart:
public function addItem(Item $item) {

    // Need the item id:
    $id = $item->getId();

    // Throw an exception if there's no id:
    if (!$id) throw new Exception('The cart requires items with unique ID
    values.');

    // Add or update:
    if (isset($this->items[$id])) {
        $this->updateItem($item, $this->items[$item]['qty'] + 1);
    } else {
        $this->items[$id] = array('item' => $item, 'qty' => 1);
        $this->ids[] = $id; // Store the id, too!
    }

    } // End of addItem() method.

    // Changes an item already in the cart:
    public function updateItem(Item $item, $qty) {

    // Need the unique item id:
    $id = $item->getId();

    // Delete or update accordingly:
    if ($qty === 0) {
        $this->deleteItem($item);
    } elseif ( ($qty > 0) && ($qty != $this->items[$id]['qty'])) {
        $this->items[$id]['qty'] = $qty;
    }

    } // End of updateItem() method.

    // Removes an item from the cart:
    public function deleteItem(Item $item) {

    // Need the unique item id:
    $id = $item->getId();

    // Remove it:
    if (isset($this->items[$id])) {
        unset($this->items[$id]);

        // Remove the stored id, too:
        $index = array_search($id, $this->ids);
        unset($this->ids[$index]);

        // Recreate that array to prevent holes:
        $this->ids = array_values($this->ids);

    }

    } // End of deleteItem() method.

    // Required by Iterator; returns the current value:
    public function current() {

    // Get the index for the current position:
    $index = $this->ids[$this->position];

    // Return the item:
    return $this->items[$index];

    } // End of current() method.

    // Required by Iterator; returns the current key:
    public function key() {
    return $this->position;
    }

    // Required by Iterator; increments the position:
    public function next() {
    $this->position++;
    }

    // Required by Iterator; returns the position to the first spot:
    public function rewind() {
    $this->position = 0;
    }

    public function valid() {
    return (isset($this->ids[$this->position]));
    }

   // Required by Countable:
   public function count() {
    return count($this->items);
   }

   } // End of ShoppingCart class.
?>

Item.php

<?php
class Item {

// Item attributes are all protected:
protected $id;
protected $name;
protected $price;

// Constructor populates the attributes:
public function __construct($id, $name, $price) {
    $this->id = $id;
    $this->name = $name;
    $this->price = $price;
}

// Method that returns the ID:
public function getId() {
    return $this->id;
}

// Method that returns the name:
public function getName() {
    return $this->name;
}

// Method that returns the price:
public function getPrice() {
    return $this->price;
}

} // End of Item class.
?>

cart.php

<?php
// Create the cart:
try {

require('includes/classes/ShoppingCart.php');
$cart = new ShoppingCart();

// Create some items:
require('includes/classes/Item.php');
$w1 = new Item('W139', 'Some Widget', 23.45);
$w2 = new Item('W384', 'Another Widget', 12.39);
$w3 = new Item('W55', 'Cheap Widget', 5.00);

// Add the items to the cart:
$cart->addItem($w1);
$cart->addItem($w2);
$cart->addItem($w3);

// Update some quantities:
$cart->updateItem($w2, 4);
$cart->updateItem($w1, 1);

// Delete an item:
$cart->deleteItem($w3);

// Show the cart contents:
echo '<h2>Cart Contents (' . count($cart) . ' items)</h2>';

if (!$cart->isEmpty()) {

foreach ($cart as $arr) {

    // Get the item object:
    $item = $arr['item'];

    // Print the item:
    printf('<p><strong>%s</strong>: %d @ $%0.2f each.<p>', $item->getName(),   
    $arr['qty'], $item->getPrice());

} // End of foreach loop!

} // End of IF.

} catch (Exception $e) {
// Handle the exception.
}
?>

UPDATE I have tried adding this code below into 'cart.php' below the items created

<table>
<tr><td><?php echo $w1; ?></td><td><button onclick="$cart- 
 >addItem($w1);">Add to cart</button></td></tr>
 <tr><td><?php echo $w2; ?></td><td><button onclick="$cart- 
 >addItem($w2);">Add to cart</button></td></tr>
 <tr><td><?php echo $w3; ?></td><td><button onclick="$cart-    
>addItem($w3);">Add to cart</button></td></tr>
</table>

However, I get this error...

Catchable fatal error: Object of class Item could not be converted to string in cart.php on line 26

You have your classes well done. Now you only have to edit the 'template' or your cart.php.

If you want to print all the items, you will have to print each item with a 'add to cart' button (in html, you can make one form per item with a 'ADD TO CART' button, passing the amount and the ID of the item. And to see what you have in the cart you have done in cart.php

foreach ($cart as $arr) {

// Get the item object:
$item = $arr['item'];

// Print the item:
printf('<p><strong>%s</strong>: %d @ $%0.2f each.<p>', $item->getName(),   
$arr['qty'], $item->getPrice());

} // End of foreach loop!

So if I understand your question, you only need a way to go adding the items to card. I would do like that.

ADDED: Of course you get that error. You cant print an object like that. I recommend you to add a function in your Item class (Item.php) like:

  public function printItem(){
         return $this->name." ".$this->price //Or whatever you want to print.
  }

The function name I put is printItem to avoid reserved words (just 'print' could be dangerous)

And then, in your template (the table) you can replace

   echo $w1 by echo $w1->printItem() //Or something like that

I Hope this will help you. =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM