Skip to content

Lab 12: Session-Based Shopping Cart

In this lab, you will build a session-based shopping cart for the customer-facing side of your e-commerce application. The cart stores items in $_SESSION using the SessionManager helper you built in Lab 4, so no new database tables are needed. You will use the existing ProductsModel to look up product details when items are added, then cache those details in the session so the cart view requires no additional database queries.

The four core operations mirror the CRUD pattern from previous labs: Add (create a cart entry), View (read and display cart contents), Update Quantity (modify an existing entry), and Remove (delete a cart entry).


By completing this lab, you will:

  • Use $_SESSION as a key-value store to persist cart data across HTTP requests.
  • Design a cart data structure that caches product details alongside quantity.
  • Build a CartController that reuses an existing model class (ProductsModel) without creating a new model.
  • Validate quantities against the stock available in the database.
  • Apply the Post-Redirect-Get (PRG) pattern across all cart-mutating operations.
  • Embed POST forms in existing public views, including cards rendered by JavaScript, to trigger state-changing controller actions.

Before starting this lab, ensure you have:


Before writing any code, understand how the cart will be stored in the session. The cart is an associative array stored under the key 'cart', where each entry is keyed by the product ID:

// What the cart looks like in $_SESSION
$_SESSION['cart'] = [
'3' => ['product_id' => 3, 'name' => 'Widget Pro', 'price' => 29.99, 'quantity' => 2],
'17' => ['product_id' => 17, 'name' => 'Gadget X', 'price' => 9.99, 'quantity' => 1],
];

Why cache name and price? When a product is added to the cart, you fetch its details from the database once and store them alongside the quantity. This way, the cart view can display product names and prices without querying the database on every page load.

Why key by product ID? Using the product ID as the array key makes it trivial to check if a product is already in the cart, update its quantity, or remove it, all in O(1) time instead of looping through the array.

The cart does not cache the stock. Stock changes as other customers buy, so add() and update() read the current stock_quantity from the database every time.


Objective: Define all the routes needed for cart operations.

Instructions:

  1. Open app/Routes/web-routes.php
  2. Add the following import at the top of the file:
use App\Controllers\CartController;
  1. Register the following five routes outside the /admin group (these are customer-facing routes):
HTTP MethodURIController MethodRoute Name
GET/cartindexcart.index
POST/cart/addaddcart.add
POST/cart/updateupdatecart.update
POST/cart/removeremovecart.remove
POST/cart/clearclearcart.clear
  1. Save the file

Objective: Build a controller that manages all cart operations using session storage.

Instructions:

  1. Navigate to app/Controllers/

  2. Create a new file named CartController.php

  3. Define the CartController class following the same pattern as ProductsController:

    • Extend BaseController and inject Container and ProductsModel in the constructor
    • Refer to Creating a Controller Class if you need a refresher on the controller structure
  4. Implement the following five methods. Use the messages from the table at the end of this step.

  • Read the cart from the session (an empty array if there is no cart yet).
  • Calculate the total number of items by summing the quantity of every entry.
  • Calculate the grand total price by summing price * quantity for every entry.
  • Render 'cart/cartIndexView.php' with the keys title ('Shopping Cart'), cart, itemCount, and grandTotal.

Method 2: add() → Add a Product to the Cart

Section titled “Method 2: add() → Add a Product to the Cart”
  • Read product_id from the submitted form and cast it to int. If it is not greater than 0, set an error flash message and redirect to cart.index.
  • Fetch the product from the database. If it does not exist, set an error flash message and redirect.
  • Read the current cart from the session.
  • Work out the new quantity: the current quantity plus 1, or 1 if the product is not in the cart yet.
  • If the new quantity is larger than the product’s stock_quantity, set an error flash message and redirect without changing the cart.
  • Otherwise, store the entry with the product’s id, name, price, and the new quantity, write the cart back to the session, and set a success flash message.
  • Redirect to cart.index.

Method 3: update() → Update Item Quantity

Section titled “Method 3: update() → Update Item Quantity”
  • Read product_id and quantity from the submitted form. Cast both to int.
  • Read the current cart from the session. If the product is not in the cart, set an error flash message and redirect.
  • If the new quantity is less than or equal to 0, remove the item from the cart and set a success flash message saying it was removed.
  • Otherwise, fetch the product from the database. If the new quantity is larger than its stock_quantity, set an error flash message and keep the old quantity. If not, update the quantity and set a success flash message.
  • Write the updated cart back to the session and redirect to cart.index.
  • Read product_id from the submitted form and cast it to int.
  • Read the current cart from the session.
  • If the product is in the cart, remove its entry, write the cart back, and set a success flash message. Otherwise, set an error flash message.
  • Redirect to cart.index.

Method 5: clear() → Empty the Entire Cart

Section titled “Method 5: clear() → Empty the Entire Cart”
  • Delete the 'cart' key from the session. Remove only that key: the session also holds the logged-in user, the language, and the flash messages.
  • Set a success flash message and redirect to cart.index.
  1. Save the file

Messages:

SituationTypeMessage
Invalid or unknown producterrorThis product does not exist.
Product addedsuccess‘Product name’ was added to your cart.
Quantity larger than the stockerrorOnly N of ‘Product name’ are in stock.
Product not in the cart (update(), remove())errorThis product is not in your cart.
Quantity updatedsuccessThe quantity of ‘Product name’ was updated.
Item removed (remove(), or quantity 0 or less)success‘Product name’ was removed from your cart.
Cart clearedsuccessYour cart has been cleared.

Use the FlashMessage helper class for every message.


Objective: Build a view that displays the cart contents with controls to update quantities and remove items.

Instructions:

  1. Create a new directory app/Views/cart/ (if it does not exist)
  2. Create a new file named cartIndexView.php inside that directory
  3. Build the view with the following structure:

Layout:

  • Use the public layout: call ViewHelper::loadHeader($title) at the top and ViewHelper::loadFooter() at the bottom.

Empty cart state:

  • If the cart is empty, display a Bootstrap info alert with the message “Your cart is empty.” and include a link back to the product listing page (APP_BASE_URL . '/products').

Cart table (when items exist):

  • Render a Bootstrap table (table table-striped table-hover) with the following columns:
ColumnContent
Product NameThe product name (escaped with hs())
Unit PriceThe price formatted with number_format($item['price'], 2)
QuantityA number <input> inside a small form (see below)
SubtotalCalculated as price * quantity, formatted with number_format()
ActionsUpdate and Remove buttons (see below)

Quantity update form:

  • In each row, the Quantity column and the “Update” button should be wrapped in a <form> that POSTs to the update route (APP_BASE_URL . '/cart/update').
  • Include a hidden input for product_id.
  • Include a number input for quantity with min="0" and the current quantity as the default value.
  • Include a submit button labeled “Update”.

Remove form:

  • In each row, the Actions column should also contain a separate <form> that POSTs to the remove route (APP_BASE_URL . '/cart/remove').
  • Include a hidden input for product_id.
  • Include a submit button labeled “Remove” (styled as a danger/red button).

Cart summary:

  • Below the table, display a row showing the grand total (passed from the controller).

Action buttons below the table:

  • A “Clear Cart” form that POSTs to the clear route (APP_BASE_URL . '/cart/clear').
  • A “Continue Shopping” link to the product listing page (APP_BASE_URL . '/products').
  1. Save the file

Step 4: Add “Add to Cart” Buttons to the Product Listing

Section titled “Step 4: Add “Add to Cart” Buttons to the Product Listing”

Objective: Add an “Add to Cart” button to every product card, including the cards created by the live search.

The products page from Lab 10 displays cards in two ways: the PHP view renders them when the page loads, and product-search.js builds new ones in JavaScript when the user searches. Both need the button.

Instructions:

  1. Open app/Views/products/userProductIndexView.php
  2. In the card-footer of the product cards inside #defaultProducts, add a small POST form next to the existing “View Details” link. The form should:
    • Set the method to POST
    • Set the action to the add-to-cart route (APP_BASE_URL . '/cart/add')
    • Contain a hidden input named product_id with the product’s id as the value
    • Contain a submit button labeled “Add to Cart” (styled as a secondary/outline button to distinguish it from “View Details”)
  3. Save the file
  4. Open public/js/product-search.js and find the card-footer in the createProductCard() function
  5. Add the same form to the template string. Build the action with window.APP_BASE_URL, and the hidden input’s value with escapeHtml(String(product.id)), as the “View Details” link next to it does
  6. Save the file

Section titled “Step 5: Add Cart Link to the Public Navigation”

Objective: Add a cart link with item count badge to the public navigation bar.

Instructions:

  1. Open your public header view (app/Views/common/header.php)

  2. Add a “Cart” link in the navigation bar that points to the cart page (APP_BASE_URL . '/cart')

  3. Display the total number of items in the cart as a Bootstrap badge next to the link:

    • Read the cart from the session (use the fully qualified class name \App\Helpers\SessionManager, since this view file has no use statements for it).
    • Sum up the quantity values to get the total item count.
    • If the item count is greater than 0, display it inside a Bootstrap badge (<span class="badge bg-danger">) next to the link text.
  4. While you are editing the public header, verify that the FlashMessage::render() call you added in Lab 8 is still present, so that flash messages display after cart operations.

  5. Save the file


Objective: Verify that all cart operations work correctly, including edge cases.

Instructions:

Test each of the following scenarios in your browser:

  1. Add a product: Click “Add to Cart” on the product listing page. Verify you are redirected to the cart page and see a success flash message. Confirm the product appears in the cart table with a quantity of 1.
  2. Add the same product again: Go back to the product listing and click “Add to Cart” on the same product. Verify the quantity increments to 2 (not a duplicate entry).
  3. Add from search results: Search for a product with the live search, then click “Add to Cart” on a result. The product should be added like any other.
  4. Update quantity: Change the quantity input to 5 and click “Update”. Verify the quantity and subtotal update correctly.
  5. Exceed the stock: In the admin panel, set a product’s stock to 3. In the cart, set its quantity to 10. You should see “Only 3 of … are in stock.” and the quantity should not change. Clicking “Add to Cart” once the cart holds 3 should show the same message.
  6. Set quantity to 0: Change the quantity to 0 and click “Update”. Verify the item is removed from the cart.
  7. Set a negative quantity: Change the quantity to a negative number and click “Update”. Verify it is treated the same as 0 (item removed).
  8. Remove an item: Add a product and click “Remove”. Verify the item is removed and a success flash message appears.
  9. Empty cart state: Remove all items from the cart. Verify the “Your cart is empty” message displays with a link back to products.
  10. Clear cart: Add multiple products, then click “Clear Cart”. Verify all items are removed at once, and that you are still logged in if you were before.
  11. Fresh session: Open the cart page in a private/incognito window (no existing session). Verify it shows the empty cart state without any errors.

Objective: Make the cart follow the language chosen with the switcher from Lab 11.

Instructions:

  1. Add a cart section to both lang/en/messages.json and lang/fr/messages.json, with a key for each text in the cart view and for each message in the table from Step 2
  2. Replace the text in cartIndexView.php and the flash messages in CartController with trans() calls
  3. Use placeholders for the product name and the stock, for example "added": "'%name%' was added to your cart.", called with trans('cart.added', ['%name%' => $product['name']])

Section titled “Step 8: (Optional) Add Cart Link to Admin Sidebar”

Objective: For convenience during development, add a link in the admin sidebar to quickly view the storefront cart.

Instructions:

  1. Open app/Views/admin/adminHeader.php
  2. Add a “View Storefront Cart” link in the sidebar navigation that points to APP_BASE_URL . '/cart'
  3. Save the file

This is useful during development because you can manage products in the admin panel and quickly switch to the customer-facing cart to test. Both the admin panel and the storefront share the same session, so items added from the public product listing are visible from any URL.


Before submitting your lab, verify the following:

  • All five cart routes are registered outside the /admin group
  • Every cart change is a POST request followed by a redirect and a flash message
  • Adding the same product twice increases its quantity instead of adding a second entry
  • A quantity can never exceed the product’s stock
  • A quantity of 0 or less removes the item
  • “Add to Cart” works on the default product cards and on the live search results
  • The navigation shows the number of items in the cart
  • Clearing the cart does not log the user out