PHP code example of tandrezone / cart-officer

1. Go to this page and download the library: Download tandrezone/cart-officer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tandrezone / cart-officer example snippets



CartOfficer\Cart;
use CartOfficer\CartController;

session_start();                   // must be called before new Cart()

$cart       = new Cart();
$controller = new CartController($cart, '/orders'); // pass your order route

$controller->handle();             // reads $_POST / JSON body, writes JSON response

 


$orderRoute = '/orders';   // shown as a hint; JS reads window.CartOfficer.orderRoute

// orders.php
$payload = json_decode($_POST['cart_payload'] ?? '{}', true);

$items      = $payload['items'];      // array of cart lines
$total      = $payload['total'];      // float grand total
$itemCount  = $payload['item_count']; // int

// … persist to DB, generate invoice, etc.

use CartOfficer\Cart;

$cart = new Cart();

$cart->add('id', 'variant', 'Name', 19.99, 2); // returns CartItem
$cart->update('id_variant', 3);                 // set quantity; 0 removes
$cart->remove('id_variant');                    // remove one line
$cart->clear();                                 // empty cart

$cart->items();   // CartItem[] keyed by "productId_variant"
$cart->count();   // total units
$cart->total();   // float grand total
$cart->isEmpty(); // bool
$cart->toArray(); // raw session array

$item->productId;      // string
$item->productVariant; // string
$item->productName;    // string
$item->price;          // float
$item->quantity;       // int
$item->lineTotal();    // float  (price × quantity)
$item->key();          // string "productId_variant"
$item->toArray();      // array

use CartOfficer\CartController;

$controller = new CartController($cart, '/orders');
$controller->handle(); // auto-dispatch on $_POST['action'] / JSON body

// Or call actions directly:
$controller->actionGet();
$controller->actionAdd();
$controller->actionUpdate();
$controller->actionDelete();
$controller->actionClear();
$controller->actionOrder();
html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Shop</title>
  <link rel="stylesheet" href="/vendor/tandrezone/cart-officer/public/css/cart.css">
</head>
<body>

  <!-- ── Header ── -->
  <header>
    <h1>My Shop</h1>

    <!-- Cart button (badge updates automatically) -->