Sunday, February 6, 2011

Building a Shopping Cart using CodeIgniter’s Shopping Cart Class

CodeIgniter Shopping cart class
Late last year CodeIgniter v1.7.2 was released with a lot of improvements and bug fixes. This version is now compatible with PHP5.3.0, they added is_php() to Common functions to facilitate PHP version comparisons, modified show_error() to allow sending of HTTP server response codes, and all internal uses now send proper status codes, Form helper improved and a new class which we are about to cover in this tutorial the Shopping Cart Class.

Class Overview from CodeIgniter User Guide section.
The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove items from the cart.
The Cart class utilizes CodeIgniter’s Session Class to save the cart information to a database, so before using the Cart class you must set up a database table as indicated in the Session Documentation , and set the session preferences in your appliction/config/config.php file to utilize a database.
To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function:
$this->load->library('cart');
Once loaded, the Cart object will be available using: $this->cart
Adding an Item to The Cart
To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert() function, as shown below:
  1. $data = array(  
  2.                'id'      => 'sku_123ABC',  
  3.                'qty'     => 1,  
  4.                'price'   => 39.95,  
  5.                'name'    => 'T-Shirt',  
  6.                'options' => array('Size' => 'L''Color' => 'Red')  
  7.             );  
  8.   
  9. $this->cart->insert($data);  
The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has options associated with it. Use an array for options, as shown above.
The five reserved indexes are:
  • id – Each product in your store must have a unique identifier. Typically this will be an “sku” or other such identifier.
  • qty – The quantity being purchased.
  • price – The price of the item.
  • name - The name of the item.
  • options – Any additional attributes that are needed to identify the product. These must be passed via an array.
Cart Class Function reference
Function Reference
» $this->cart->insert();
Permits you to add items to the shopping cart.
» $this->cart->update();
Permits you to update items in the shopping cart.
» $this->cart->total();
Displays the total amount in the cart.
» $this->cart->total_items();
Displays the total number of items in the cart.
» $this->cart->contents();
Returns an array containing everything in the cart.
» $this->cart->has_options(rowid);
Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.
» $this->cart->options(rowid);
Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.
» $this->cart->destroy();
Permits you to destroy the cart. This function will likely be called when you are finished processing the customer’s order.

Lets Make our Simple Shopping Cart

Lets start to by creating our Product controller
  1. function Products(){  
  2.   
  3.     parent::Controller();  
  4.   
  5.     //load the cart library  
  6.     //you can do this to your autoload.php  
  7.     $this->load->library('cart');  
  8.     $this->load->helper('url');  
  9. }  
  10.   
  11. function index(){  
  12.   
  13.     //pull the list of products from your database.  
  14.   
  15.     $vars['pList'] = $this->productModel->getProducts();  
  16.   
  17.     //pList should have your product details. (product id, description, price, product image, etc.)  
  18.     //load the view then pass the product data.  
  19.   
  20.     $this->load->view('product_view'$vars);  
  21. }  
  22.   
  23. function addToCart($productId) {  
  24.   
  25.     //you need the details for the selected products to be added to your cart  
  26.   
  27.     $item = $this->productModel->getProductById($productId);  
  28.   
  29.     //$item variable must have the 4 required indexes necessary for inserting data to our cart.  
  30.   
  31.     //sample  
  32.   
  33.     /* $item =  array( 
  34.               'id'      => 'sku_123ABC', 
  35.               'qty'     => 1, 
  36.               'price'   => 99.99, 
  37.               'name'    => 'Monitor', 
  38.               'options' => array('Color' => 'Black') 
  39.            ); 
  40.     */  
  41.   
  42.     //insert item to cart  
  43.   
  44.     $this->cart->insert($item);  
  45.   
  46.     //after a user click the add to cart button in our product page we could redirect him  
  47.     //back to our product page  
  48.   
  49.     redirect('products');  
  50.   
  51.     //but if you use ajax to add item to your cart maybe you could use an echo fucntion.  
  52.   
  53. }  
And then our cart controller
  1. function Cart(){  
  2.     parent::Controller();  
  3.   
  4.     $this->load->library('cart');  
  5.     $this->load->helper('form');  
  6.     $this->load->helper('url');  
  7.   
  8. }  
  9.   
  10. function index(){  
  11.   
  12.     //load your cart view  
  13.   
  14.     $this->load->view('cart_view');  
  15.   
  16. }  
  17.   
  18. function updateCart(){  
  19.   
  20.     //To update the information in your cart, you must pass an array containing the Row ID  
  21.     //and quantity to the $this->cart->update() function.  
  22.   
  23.     //ID and the Quantity can be pass by submiting the form in our cart view.  
  24.   
  25.     //Our cart view can generate a data like this  
  26.     //I try add an item to cart then try to submit the form and using var dump I got something like this  
  27.     /* 
  28.     Array ( 
  29.         [1] => Array ( 
  30.                 [rowid] => 79fcbc10fafd6b1ea8202991ba15502c 
  31.                 [qty] => 12 ) 
  32.         [2] => Array ( 
  33.                 [rowid] => e942e3675eab2e6e688bdf6a851a0a54 
  34.                 [qty] => 34 ) 
  35.         ) 
  36.     */  
  37.   
  38.     if($_POST){  
  39.   
  40.         $data = $_POST//for the sake of this example we are going to use the $_POST variable directly  
  41.   
  42.     }  
  43.   
  44.     $this->cart->update($data);  
  45.   
  46.     redirect('cart');  
  47. }  
And finally our Cart View
  1. <?php echo form_open('cart/updatecart'); ?>  
  2. <table cellpadding="6" cellspacing="1" style="width:100%" border="1">  
  3. <tr>  
  4.   <th>QTY</th>  
  5.   <th>Item Description</th>  
  6.   <th style="text-align:right">Item Price</th>  
  7.   <th style="text-align:right">Sub-Total</th>  
  8.   </tr>  
  9. <?php $i = 1; ?>  
  10. <?php foreach($this->cart->contents() as $items): ?>  
  11.  <?php echo form_hidden($i.'[rowid]'$items['rowid']); ?>  
  12.   
  13.   <tr>  
  14.   <td><?php echo form_input(array('name' => $i.'[qty]''value' => $items['qty'], 'maxlength' => '3',
  15.  'size' => '5')); ?></td>  
  16.   <td>  
  17.   <?php echo $items['name']; ?>  
  18.   
  19.   <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>  
  20.   
  21.   <p>  
  22.   <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>  
  23.   
  24.   <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />  
  25.   
  26.   <?php endforeach; ?>  
  27.   </p>  
  28.   
  29.   <?php endif; ?>  
  30.   
  31.   </td>  
  32.   <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>  
  33.   <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>  
  34.   </tr>  
  35. <?php $i++; ?>  
  36. <?php endforeach; ?>  
  37. <tr>  
  38.   <td colspan="2"> </td>  
  39.   <td ><strong>Total</strong></td>  
  40.   <td >$<?php echo $this->cart->format_number($this->cart->total()); ?></td>  
  41.   </tr>  
  42. </table>  
  43. <p><?php echo form_submit('''Update your Cart'); ?></p>  
And then a sample of a product View. What is important here is show how our addtocart function being called.
  1. <table>  
  2.   <tr>  
  3.   <td>Name</td>  
  4.   <td>Desc</td>  
  5.   <td>Price</td>  
  6.   <td></td>  
  7.   </tr>  
  8. <?php foreach ($pList as $item) { ?>  
  9.  <tr>  
  10.   <td><?php echo $item['name']; ?></td>  
  11.   <td><?php echo $item['desc']; ?></td>  
  12.   <td><?php echo $item['price']; ?></td>  
  13.   <td><a href="addtocart/<?php echo $item['id']; ?>">Add To cart</a></td>  
  14.   </tr>  
  15.   
  16. <?php } ?>  
  17. </table>  
Subscribe to my RSS for more.

No comments:

Post a Comment