PHP code example of ttpryg / cart-engine

1. Go to this page and download the library: Download ttpryg/cart-engine 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/ */

    

ttpryg / cart-engine example snippets


use Ttpryg\CartEngine\Services\CartService;
use Ttpryg\CartEngine\Storage\FileCartStorage;
use Ttpryg\CartEngine\Entities\CartCondition;

// Initialize File Cache Storage
$storage = new FileCartStorage(__DIR__ . '/storage/carts');
$cartService = new CartService($storage);

$cartId = 'user_session_abc123';

// Add Product to Cart
$cartService->addItem(
    cartId: $cartId,
    itemType: 'product',
    itemId: 101,
    name: 'Nike Running Shoes',
    unitPrice: 1500000.0,
    quantity: 1,
    attributes: ['color' => 'Black', 'size' => '42']
);

// Apply Discount Voucher (-10%)
$cartService->applyCondition($cartId, new CartCondition('VOUCHER10', 'discount', '-10%'));

// Get Totals
$totals = $cartService->getTotals($cartId);
echo $totals->grandTotal; // 1,350,000

use PDO;
use Ttpryg\CartEngine\Services\CartService;
use Ttpryg\CartEngine\Storage\PdoCartStorage;
use Ttpryg\CartEngine\Entities\CartCondition;

$pdo = new PDO("mysql:host=localhost;dbname=my_db", "root", "secret");
$storage = new PdoCartStorage($pdo);
$cartService = new CartService($storage);

$cartId = 'booking_session_xyz';

// Add Hotel Room Reservation (3.5 Nights)
$cartService->addItem(
    cartId: $cartId,
    itemType: 'hotel_room',
    itemId: 'deluxe_suite',
    name: 'Deluxe Suite Sea View',
    unitPrice: 500000.0,
    quantity: 3.5,
    attributes: ['check_in' => '2026-10-01 14:00', 'check_out' => '2026-10-05 02:00']
);

// Apply PPN Tax (+11%)
$cartService->applyCondition($cartId, new CartCondition('PPN 11%', 'tax', '+11%'));

// Checkout & Export Snapshot
$orderSnapshot = $cartService->checkout($cartId);