Understanding CodeIgniter Cart Class

August 4th, 2010 by aditia rahman / 1 Comment  

     

CodeIgniter Cart ClassCart is one of the most important feature when creating an online store. In this post I want to have more understanding about Cart Class in CodeIgniter, cause maybe come in handy in the future, you can see how many new online store out there open in business, and in this internet age, online store seems the must have for many people who have retail business, in this post I’m not writing about how to use it in some example, the code I posted in here just copying from the original cart class documentation, but i’m included the link to the example usage of this class on the section 4 below.

1. What is Cart Class in CodeIgniter?

First from the official documentation

- 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. -

which mean this class save the cart from the users and save it to database, you have to create this table

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
	session_id varchar(40) DEFAULT '0' NOT NULL,
	ip_address varchar(16) DEFAULT '0' NOT NULL,
	user_agent varchar(50) NOT NULL,
	last_activity int(10) unsigned DEFAULT 0 NOT NULL,
	user_data text NOT NULL,
	PRIMARY KEY (session_id)
);

You can change the table name, but it have to be adapted to the config.php

$config['sess_cookie_name']		= 'ci_session';
$config['sess_expiration']		= 7200;
$config['sess_encrypt_cookie']	= FALSE;
$config['sess_use_database']	= FALSE;
$config['sess_table_name']		= 'ci_sessions';
$config['sess_match_ip']		= FALSE;
$config['sess_match_useragent']	= TRUE;
$config['sess_time_to_update'] 	= 300;

When you add an array data to the cart class, the data would be inserted to ci_sessions table in user_data field. Saving data to cart class is have to be in array format, it can be single or multidimensional array, this code I take from the original documentation

// the single array
$data = array(
   'id'      => 'sku_123ABC',
   'qty'     => 1,
   'price'   => 39.95,
   'name'    => 'T-Shirt',
   'options' => array('Size' => 'L', 'Color' => 'Red')
);

// the multidimensional array
$data = array(
   array(
           'id'      => 'sku_123ABC',
           'qty'     => 1,
           'price'   => 39.95,
           'name'    => 'T-Shirt',
           'options' => array('Size' => 'L', 'Color' => 'Red')
        ),
   array(
           'id'      => 'sku_567ZYX',
           'qty'     => 1,
           'price'   => 9.95,
           'name'    => 'Coffee Mug'
        ),
   array(
           'id'      => 'sku_965QRS',
           'qty'     => 1,
           'price'   => 29.95,
           'name'    => 'Shot Glass'
        )
);

// insert the data
$this->cart->insert($data);

The required index in the array are id, qty, price, name you can add the additional index but you can’t use that four index and the options index is optional, in case you want to save another information of the product for example, T-Shirt with the same product id but different size. The last thing from the array is you can’t use another words that reserved, they are rowid and subtotal.

2. Displaying The Items

<?php echo form_open('path/to/controller/update/function'); ?>

<table cellpadding="6" cellspacing="1" style="width:100%" border="0">

<tr>
  <th>QTY</th>
  <th>Item Description</th>
  <th style="text-align:right">Item Price</th>
  <th style="text-align:right">Sub-Total</th>
</tr>

<?php $i = 1; ?>

<?php foreach($this->cart->contents() as $items): ?>

	<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>

	<tr>
	  <td><?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
	  <td>
		<?php echo $items['name']; ?>

			<?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>

				<p>
					<?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>

						<strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />

					<?php endforeach; ?>
				</p>

			<?php endif; ?>

	  </td>
	  <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
	  <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
	</tr>

<?php $i++; ?>

<?php endforeach; ?>

<tr>
  <td colspan="2"> </td>
  <td class="right"><strong>Total</strong></td>
  <td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>

</table>

<p><?php echo form_submit('', 'Update your Cart'); ?></p>

The code above is to displaying the current cart on the web pages, and theres a hidden field on the form this is used when we want to updating the cart, the difference between insert and update is, insert function is to adding new items to the cart, yet the update function is to updating items on the cart whether the quantity the options or something else, so when you updating the cart you need the rowid to pass it through. Here is the code

$data = array(
   'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
   'qty'   => 3
);

$this->cart->update($data);

// or a multi-dimensional array

$data = array(
   array(
           'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
           'qty'     => 3
        ),
   array(
           'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
           'qty'     => 4
        ),
   array(
           'rowid'   => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
           'qty'     => 2
        )
);

$this->cart->update($data);

3. The Available Function

$this->cart->insert();
- Permits you to add items to the shopping cart, as outlined above. -

$this->cart->update();
- Permits you to update items in the shopping cart, as outlined above. -

$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. -

$this->cart->product_options(rowid);
- This function not described in the documentation but used in the example, this is to get the available options on the product. -

4. The Examples

I’m not providing any code from this post, these tutorial below can provide you to get started with this cart class. Maybe I’ll post the different tutorial from these. Just enjoy it.

CodeIgniter From Scratch: Shopping Cart ( link )

net.tutsplus.com tutorials php codeigniter from scratch shopping cart

How to Build a Shopping Cart using CodeIgniter and jQuery ( link )

net.tutsplus.com tutorials php how to build a shopping cart using codeigniter and jquery

        submit to reddit Delicious

Others You May Like

One Comment Leave a Comment Subscribe RSS

Leave a Comment

You must be logged in to post a comment.