Lab 12: Session-Based Shopping Cart
Additional Resources
Section titled “Additional Resources”- Lab 4: Session Middleware and Flash Messages
- Lab 10: Live Search with AJAX
- Working with the BaseController class
- Working with the BaseModel class
- PHP Sessions ↗
- Bootstrap Tables ↗
- Post-Redirect-Get Pattern ↗
Overview
Section titled “Overview”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).
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Use
$_SESSIONas a key-value store to persist cart data across HTTP requests. - Design a cart data structure that caches product details alongside quantity.
- Build a
CartControllerthat 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.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 4: Session Middleware and Flash Messages (SessionManager, SessionMiddleware, and the FlashMessage helper class).
- Completed Lab 6 (
ProductsModel::findById()). - Completed Lab 10: Live Search with AJAX (the public
/productspage andpublic/js/product-search.js). - The
productstable in your database with sample data, includingstock_quantityvalues.
Cart Data Structure
Section titled “Cart Data Structure”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.
Lab Steps
Section titled “Lab Steps”Step 1: Register Cart Routes
Section titled “Step 1: Register Cart Routes”Objective: Define all the routes needed for cart operations.
Instructions:
- Open
app/Routes/web-routes.php - Add the following import at the top of the file:
use App\Controllers\CartController;- Register the following five routes outside the
/admingroup (these are customer-facing routes):
| HTTP Method | URI | Controller Method | Route Name |
|---|---|---|---|
| GET | /cart | index | cart.index |
| POST | /cart/add | add | cart.add |
| POST | /cart/update | update | cart.update |
| POST | /cart/remove | remove | cart.remove |
| POST | /cart/clear | clear | cart.clear |
- Save the file
Step 2: Create the CartController
Section titled “Step 2: Create the CartController”Objective: Build a controller that manages all cart operations using session storage.
Instructions:
-
Navigate to
app/Controllers/ -
Create a new file named
CartController.php -
Define the
CartControllerclass following the same pattern asProductsController:- Extend
BaseControllerand injectContainerandProductsModelin the constructor - Refer to Creating a Controller Class if you need a refresher on the controller structure
- Extend
-
Implement the following five methods. Use the messages from the table at the end of this step.
Method 1: index() → Display the Cart
Section titled “Method 1: index() → Display the Cart”- Read the cart from the session (an empty array if there is no cart yet).
- Calculate the total number of items by summing the
quantityof every entry. - Calculate the grand total price by summing
price * quantityfor every entry. - Render
'cart/cartIndexView.php'with the keystitle('Shopping Cart'),cart,itemCount, andgrandTotal.
Method 2: add() → Add a Product to the Cart
Section titled “Method 2: add() → Add a Product to the Cart”- Read
product_idfrom the submitted form and cast it toint. If it is not greater than 0, set an error flash message and redirect tocart.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_idandquantityfrom the submitted form. Cast both toint. - 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.
Method 4: remove() → Remove an Item
Section titled “Method 4: remove() → Remove an Item”- Read
product_idfrom the submitted form and cast it toint. - 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.
- Save the file
Messages:
| Situation | Type | Message |
|---|---|---|
| Invalid or unknown product | error | This product does not exist. |
| Product added | success | ‘Product name’ was added to your cart. |
| Quantity larger than the stock | error | Only N of ‘Product name’ are in stock. |
Product not in the cart (update(), remove()) | error | This product is not in your cart. |
| Quantity updated | success | The quantity of ‘Product name’ was updated. |
Item removed (remove(), or quantity 0 or less) | success | ‘Product name’ was removed from your cart. |
| Cart cleared | success | Your cart has been cleared. |
Use the FlashMessage helper class for every message.
Step 3: Create the Cart View
Section titled “Step 3: Create the Cart View”Objective: Build a view that displays the cart contents with controls to update quantities and remove items.
Instructions:
- Create a new directory
app/Views/cart/(if it does not exist) - Create a new file named
cartIndexView.phpinside that directory - Build the view with the following structure:
Layout:
- Use the public layout: call
ViewHelper::loadHeader($title)at the top andViewHelper::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:
| Column | Content |
|---|---|
| Product Name | The product name (escaped with hs()) |
| Unit Price | The price formatted with number_format($item['price'], 2) |
| Quantity | A number <input> inside a small form (see below) |
| Subtotal | Calculated as price * quantity, formatted with number_format() |
| Actions | Update 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
quantitywithmin="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').
- 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:
- Open
app/Views/products/userProductIndexView.php - In the
card-footerof the product cards inside#defaultProducts, add a small POST form next to the existing “View Details” link. The form should:- Set the
methodtoPOST - Set the
actionto the add-to-cart route (APP_BASE_URL . '/cart/add') - Contain a hidden input named
product_idwith the product’sidas the value - Contain a submit button labeled “Add to Cart” (styled as a secondary/outline button to distinguish it from “View Details”)
- Set the
- Save the file
- Open
public/js/product-search.jsand find thecard-footerin thecreateProductCard()function - Add the same form to the template string. Build the
actionwithwindow.APP_BASE_URL, and the hidden input’s value withescapeHtml(String(product.id)), as the “View Details” link next to it does - Save the file
Step 5: Add Cart Link to the Public Navigation
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:
-
Open your public header view (
app/Views/common/header.php) -
Add a “Cart” link in the navigation bar that points to the cart page (
APP_BASE_URL . '/cart') -
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 nousestatements for it). - Sum up the
quantityvalues 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.
- Read the cart from the session (use the fully qualified class name
-
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. -
Save the file
Step 6: Test and Handle Edge Cases
Section titled “Step 6: Test and Handle Edge Cases”Objective: Verify that all cart operations work correctly, including edge cases.
Instructions:
Test each of the following scenarios in your browser:
- 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.
- 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).
- 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.
- Update quantity: Change the quantity input to 5 and click “Update”. Verify the quantity and subtotal update correctly.
- 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.
- Set quantity to 0: Change the quantity to 0 and click “Update”. Verify the item is removed from the cart.
- Set a negative quantity: Change the quantity to a negative number and click “Update”. Verify it is treated the same as 0 (item removed).
- Remove an item: Add a product and click “Remove”. Verify the item is removed and a success flash message appears.
- Empty cart state: Remove all items from the cart. Verify the “Your cart is empty” message displays with a link back to products.
- 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.
- Fresh session: Open the cart page in a private/incognito window (no existing session). Verify it shows the empty cart state without any errors.
Step 7: (Optional) Translate the Cart
Section titled “Step 7: (Optional) Translate the Cart”Objective: Make the cart follow the language chosen with the switcher from Lab 11.
Instructions:
- Add a
cartsection to bothlang/en/messages.jsonandlang/fr/messages.json, with a key for each text in the cart view and for each message in the table from Step 2 - Replace the text in
cartIndexView.phpand the flash messages inCartControllerwithtrans()calls - Use placeholders for the product name and the stock, for example
"added": "'%name%' was added to your cart.", called withtrans('cart.added', ['%name%' => $product['name']])
Step 8: (Optional) Add Cart Link to Admin Sidebar
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:
- Open
app/Views/admin/adminHeader.php - Add a “View Storefront Cart” link in the sidebar navigation that points to
APP_BASE_URL . '/cart' - 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.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
- All five cart routes are registered outside the
/admingroup - 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