CodeIgniter 4 Shopping Cart Class

A flexible cart library for CodeIgniter 4 that maintains items in a session

v1.x PHP 7.4+ Active

Important Notice

The Cart Class ONLY provides the core "cart" functionality. It does not provide:

Core Functionality

This library focuses exclusively on managing the shopping cart session data. You'll need to implement other e-commerce features separately.

Using the Cart Class

Adding Items to Cart

To add an item to the shopping cart, pass an array with product information to the insert() method:

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

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

Required Fields

The first four array indexes (id, qty, price, and name) are required. The fifth index (options) is optional for product variations.

Adding Multiple Items

Add multiple products at once using a multi-dimensional array:

$data = array(
  array(
    'id' => 'sku_123ABC',
    'qty' => 1,
    'price' => 39.95,
    'name' => 'T-Shirt''
  ),
  array(
    'id' => 'sku_567ZYX',
    'qty' => 1,
    'price' => 9.95,
    'name' => 'Coffee Mug''
  )
);

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

Displaying the Cart

Create a view file to display cart contents:

<table cellpadding="6" cellspacing="1" style="width:100%">
  <tr>
    <th>QTY</th>
    <th>Item Description</th>
    <th>Item Price</th>
    <th>Sub-Total</th>
  </tr>

  <?php foreach ($cart->contents() as $items):?>
  <tr>
      <td><input type="number" value="<?php echo $items['qty'];?>"></td>
  <td>
    <?php echo $items['name']; ?>
    <?php if ($cart->has_options($items['rowid'])): ?>
    <?php foreach($cart->product_options($items['rowid']) as $option_name => $option_value):?>
      <?php echo $option_name; ?>
      <?php echo $option_value; ?>
    <?php endforeach; ?>
    <?php endif; ?>
  </td>
    <td style="text-align:right"><?php echo $cart->format_number($items['price']); ?> </td>
    <td style="text-align:right" ><?php echo $cart->format_number($items['subtotal']); ?></td>
  </tr>
  <?php endforeach; ?>

  <tr>
    <td colspan="3"></td>
    <td style="text-align:right"> Total: ₺ <?php echo $cart->format_number($cart->total()); ?></td>
  </tr>
</table>
    

Updating the Cart

Update cart items by passing the Row ID and updated properties:

// Single item update
$data = array(
  'rowid' =>
  'b99ccdf16028f015540f341130b6d8ec',
  'qty' => 3
);

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

// Multiple items update
$data = array(
  array(
    'rowid' =>
    'b99ccdf16028f015540f341130b6d8ec',
    'qty' => 3
  ), array(
    'rowid' =>
    'xw82g9q3r495893iajdh473990rikw23',
    'qty' => 4
  )
);

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

Row ID Note

If quantity is set to zero, the item will be removed from the cart. The Row ID is generated automatically when items are added to uniquely identify product variations.

Initializing the Cart

Database Requirement

The Cart class uses CodeIgniter's Session Class which requires a database table. Set up the session table as indicated in the Session Documentation and configure your .env file to use database sessions.

Composer Installation

Install the package via Composer:

composer require bertugfahriozer/ci4shoppingcart

After installation, you'll see an example directory that you can reference or copy into your project.

Controller Setup

Initialize the Cart class in your controller constructor:

use ci4shoppingcart\Libraries\Cart;

public $cart;

public function __construct(){
  $this->cart = new Cart();
}
          

Once loaded, access the Cart object via:

$this->cart

Session Auto-Load

The Cart Class automatically loads and initializes the Session Class, so you don't need to load it separately unless you're using sessions elsewhere in your application.

Class Reference

Properties

Property Default Description
$product_id_rules '.a-z0-9_-' Regex rules for validating product IDs (alphanumeric, dashes, underscores, periods)
$product_name_rules 'w -.:' Regex rules for validating product names (alphanumeric, dashes, underscores, colons, periods)
$product_name_safe TRUE Whether to only allow "safe" product names

Methods

Method Parameters Returns Description
insert() $items (array) bool Adds items to cart, returns TRUE on success
update() $items (array) bool Updates cart items by Row ID
remove() $rowid (string) bool Removes item by Row ID
total() - float Returns cart total amount
total_items() - int Returns total item count in cart
contents() [$newest_first = FALSE] array Returns all cart items, optionally sorted
get_item() $row_id (string) array|bool Returns item data by Row ID or FALSE
has_options() $row_id (string) bool Checks if item has options
product_options() $row_id (string) array Returns item options by Row ID
destroy() - void Empties the entire cart

Understanding Row ID

The Row ID is a unique identifier generated when items are added to the cart. It allows the cart to manage identical products with different options (like size or color variations).

For example, if a customer adds two identical t-shirts (same product ID) in different sizes, the cart generates unique Row IDs for each variation. This ensures each item can be managed independently.

In most cases, you'll only need to work with Row IDs when updating or removing items from the cart view page.