Skip to Content
Course content

193: Building a Shopping Cart Session Manager

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've touched on how sessions work in a vacuum, but now it's time to put them to work in a scenario you'll encounter in almost every e-commerce project: the shopping cart. The challenge here isn't just storing data, but managing a state that changes as the user browses. We need a way to add items, update quantities, and keep that data persistent across different pages without hitting the database every single time a user clicks "Add to Cart".

Structuring the Cart in the Session

I prefer to keep the cart as an associative array inside the $_SESSION superglobal. The key should be the product ID, and the value should be the quantity. This makes it incredibly easy to check if an item is already in the cart without looping through the whole list. If the ID exists as a key, we just increment the value.

The "Wipeout" Mistake

Now, here is where I messed up the first time I built this years ago. I tried to be "efficient" by writing the addition in a single line, thinking I could just assign the value directly. I wrote something like $_SESSION['cart'] = [$productId => $quantity];.

Of course, that was a disaster. Every time a user added a second item to their cart, the first item vanished. I wasn't appending to the array; I was overwriting the entire cart with a new array containing only the most recent item. It's a classic "junior" mistake, but it happens to the best of us when we're rushing. The key is to remember that $_SESSION is just a persistent array—treat it with the same care you'd treat any other PHP array.

Calculating Totals from Session Data

Once the items are in the session, the next step is actually making them useful. You don't want to store prices in the session because prices change in the database, and a user could potentially manipulate their session data to get a discount. Instead, we store the IDs and quantities in the session, then fetch the current prices from our "database" (or a mock array for this example) during the checkout phase.

 ['name' => 'Mechanical Keyboard', 'price' => 89.99],
    102 => ['name' => 'Gaming Mouse', 'price' => 45.00],
    103 => ['name' => 'UltraWide Monitor', 'price' => 320.00],
];

$cart = $_SESSION['cart'] ?? [];
$grandTotal = 0;

echo "

Your Cart

    "; foreach ($cart as $id => $quantity) { if (isset($products[$id])) { $itemTotal = $products[$id]['price'] * $quantity; $grandTotal += $itemTotal; echo "
  • {$products[$id]['name']} x $quantity: $" . number_format($itemTotal, 2) . "
  • "; } } echo "
Total: $" . number_format($grandTotal, 2) . ""; ?>

By keeping the session lean—only storing IDs and quantities—we keep the session file size small and ensure that the price is always pulled from the source of truth right before the user pays.




📋 Practical Task

Implementing the Cart Item Removal System

Your task is to extend the CartManager class we built in this lesson. Currently, we can add items, but we can't remove them. Create a new method inside the CartManager class called remove($productId) that deletes a specific product from the session cart using unset(). Additionally, create a method called clear() that completely empties the cart. Test your code by adding three different items to the session and then removing only one of them to ensure the others remain intact.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.