Courses/PHP/E-Commerce Logic

    Lesson 39 โ€ข Advanced

    E-Commerce Logic ๐Ÿ›’

    Model shopping carts with coupons, build order processing pipelines with inventory checks, and generate professional invoices.

    What You'll Learn in This Lesson

    • โ€ข Build a shopping cart with add, remove, and quantity updates
    • โ€ข Apply coupon codes with percentage discounts
    • โ€ข Calculate subtotals, tax, and grand totals
    • โ€ข Process orders through a status lifecycle
    • โ€ข Generate formatted invoices and track order timelines

    Shopping Cart System

    A cart needs to handle adding items (merging duplicates), updating quantities, removing items, and applying discount coupons. Store prices in cents (integers) to avoid floating-point rounding errors โ€” $29.99 becomes 2999. Calculate tax only on the discounted subtotal.

    Try It: Shopping Cart

    Build a cart with items, coupons, tax calculation, and totals

    Try it Yourself ยป
    JavaScript
    // Shopping Cart System in PHP
    console.log("=== Building a Shopping Cart ===");
    console.log();
    
    class ShoppingCart {
      constructor(userId) {
        this.userId = userId;
        this.items = [];
        this.coupon = null;
      }
    
      addItem(product, quantity) {
        let existing = this.items.find(i => i.product.id === product.id);
        if (existing) {
          existing.quantity += quantity;
          console.log("  ๐Ÿ“ฆ Updated: " + product.name + " ร— " + existing.quantity);
        } else {
          this.items.push({ product,
    ...

    Orders & Invoices

    Orders have a lifecycle: pending โ†’ paid โ†’ processing โ†’ shipped โ†’ delivered. Each status change creates a timeline entry for customer tracking. Inventory checks prevent overselling, and invoices provide a permanent record of the transaction for accounting and tax purposes.

    Try It: Order Processing

    Check inventory, process orders through lifecycle, and generate invoices

    Try it Yourself ยป
    JavaScript
    // Order Processing & Invoice Generation
    console.log("=== Order Lifecycle ===");
    console.log();
    
    class Order {
      constructor(cart, customer, shippingAddress) {
        this.id = "ORD-" + Date.now().toString(36).toUpperCase();
        this.items = cart.items.map(i => ({
          productId: i.product.id,
          name: i.product.name,
          price: i.product.price,
          quantity: i.quantity,
          lineTotal: i.product.price * i.quantity,
        }));
        this.customer = customer;
        this.shipping = shippingAddress
    ...

    โš ๏ธ Common Mistakes

    โš ๏ธ
    Using floats for money โ€” 0.1 + 0.2 !== 0.3 in JavaScript and PHP. Store prices as integers (cents) and divide by 100 only for display.
    โš ๏ธ
    Not locking inventory โ€” Two users can buy the last item simultaneously. Use database transactions with SELECT ... FOR UPDATE to prevent race conditions.
    ๐Ÿ’ก
    Pro Tip: Store cart in the database (not just session) so it persists across devices. When a user logs in on their phone, their desktop cart appears.

    ๐Ÿ“‹ Quick Reference โ€” E-Commerce

    ConceptDescription
    CartTemporary collection of items before checkout
    OrderConfirmed purchase with payment and shipping
    SKUStock Keeping Unit โ€” unique product identifier
    Idempotent PaymentEnsure charge happens exactly once
    Cents (integers)Store money as integers to avoid float errors

    ๐ŸŽ‰ Lesson Complete!

    You can now build e-commerce systems! Next, learn server-side rendering with template engines like Twig.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service