PHP code example of renatoandradeweb / modern-cart
1. Go to this page and download the library: Download renatoandradeweb/modern-cart 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/ */
renatoandradeweb / modern-cart example snippets
use ModernCart\Cart;
use ModernCart\CartItem;
use ModernCart\Storage\SessionStore;
// Create a cart with session storage
$cart = new Cart('user_123', new SessionStore());
// Add items
$item = new CartItem([
'name' => 'Awesome Product',
'price' => 29.99,
'tax' => 3.00,
'quantity' => 2
]);
$cart->add($item)->save();
// Get totals
echo "Items: " . $cart->totalItems(); // 2
echo "Subtotal: $" . $cart->subtotal(); // $59.98
echo "Tax: $" . $cart->tax(); // $6.00
echo "Total: $" . $cart->total(); // $65.98
use ModernCart\Cart;
use ModernCart\Storage\{SessionStore, CookieStore, FileStore, MemoryStore};
// Session storage (recommended for web applications)
$cart = new Cart('cart_id', new SessionStore());
// Cookie storage (for persistent carts)
$cart = new Cart('cart_id', new CookieStore(
prefix: 'cart_',
expiry: 2592000, // 30 days
path: '/',
secure: true,
httpOnly: true
));
// File storage (for server-side persistence)
$cart = new Cart('cart_id', new FileStore('/path/to/storage'));
// Memory storage (for testing)
$cart = new Cart('cart_id', new MemoryStore());
// Add items
$cart->add($item);
// Update quantity
$cart->updateQuantity($item->getId(), 5);
// Update any property
$cart->update($item->getId(), 'price', 29.99);
// Remove items
$cart->remove($item->getId());
// Check if item exists
if ($cart->has($item->getId())) {
// Item exists
}
// Get specific item
$foundItem = $cart->get($item->getId());
// Clear cart
$cart->clear();
// Counts
$cart->totalItems(); // Total quantity of all items
$cart->totalUniqueItems(); // Number of different items
$cart->isEmpty(); // Check if cart is empty
$cart->isNotEmpty(); // Check if cart has items
// Prices
$cart->subtotal(); // Total excluding tax
$cart->tax(); // Total tax
$cart->total(); // Total including tax
// Get all items
$items = $cart->all(); // Returns CartItem[]
// Filter items
$expensiveItems = $cart->filter(fn($item) => $item->getPrice() > 50);
// Find first item matching condition
$firstElectronic = $cart->first(fn($item) => $item->get('category') === 'Electronics');
// Manual save
$cart->save();
// Auto-save (saves automatically when cart is destroyed)
// No action needed - cart saves on __destruct if dirty
// Restore from storage
$cart->restore();
// Refresh (discard unsaved changes)
$cart->refresh();
// Check if cart has unsaved changes
if ($cart->isDirty()) {
$cart->save();
}
use ModernCart\Contracts\Store;
class DatabaseStore implements Store
{
public function __construct(
private PDO $pdo
) {}
public function get(string $cartId): string
{
$stmt = $this->pdo->prepare('SELECT data FROM carts WHERE id = ?');
$stmt->execute([$cartId]);
return $stmt->fetchColumn() ?: serialize([]);
}
public function put(string $cartId, string $data): void
{
$stmt = $this->pdo->prepare(
'INSERT INTO carts (id, data) VALUES (?, ?)
ON DUPLICATE KEY UPDATE data = VALUES(data)'
);
$stmt->execute([$cartId, $data]);
}
public function flush(string $cartId): void
{
$stmt = $this->pdo->prepare('DELETE FROM carts WHERE id = ?');
$stmt->execute([$cartId]);
}
public function exists(string $cartId): bool
{
$stmt = $this->pdo->prepare('SELECT 1 FROM carts WHERE id = ?');
$stmt->execute([$cartId]);
return $stmt->fetchColumn() !== false;
}
}
$fileStore = new FileStore(
storagePath: '/var/cart-storage',
prefix: 'cart_',
extension: '.dat'
);
// Clean up old files (older than 30 days)
$cleaned = $fileStore->cleanup(2592000);
// Old way
$cart->add($cartItem);
$existingItem = $cart->find($itemId);
$existingItem->quantity += $cartItem->quantity;
// New way
$cart->add($cartItem); // Automatically handles quantity merging
// Old way
$item->price = 29.99;
// New way
$item->setPrice(29.99);
// or
$cart->update($itemId, 'price', 29.99);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.