mindy / cart
购物车组件
2.2.1
2018-02-22 12:34 UTC
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^6.5
- symfony/http-foundation: ~3.0
Suggests
- symfony/http-foundation: Cart component with symfony session storage
This package is not auto-updated.
Last update: 2024-09-15 04:49:14 UTC
README
安装
composer require mindy/cart --prefer-dist
使用
初始化购物车
目前可用2个存储库 SymfonySessionStorage
和 NativeSessionStorage
。
// Symfony $session = new Session(new MockArraySessionStorage()); $cart = new Cart(new SymfonySessionStorage($session));
// Native $_SESSION $cart = new Cart(new NativeSessionStorage());
添加商品
创建简单的商品类
<?php declare(strict_types=1); use Mindy\Cart\ProductInterface; class SimpleProduct implements ProductInterface { /** * @var float */ protected $price; /** * @var string */ protected $uniqueId; /** * SimpleProduct constructor. * * @param array $data */ public function __construct(array $data) { foreach ($data as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } } /** * {@inheritdoc} */ public function getPrice(): float { return (float) $this->price; } /** * {@inheritdoc} */ public function getUniqueId(): string { return $this->uniqueId; } }
使用
<?php // Добавление позиции $product = new SimpleProduct(['price' => 100, 'uniqueId' => 'foo']); $quantity = 2; $options = ['cpu' => 'xeon', 'memory' => '4']; $cart->add($product, $quantity, $options); assert(1, count($cart->all())); $cart->add($product, $quantity, $options); assert(2, count($cart->all())); $cart->add($product, $quantity, $options, true); // Замена позиции assert(1, count($cart->all())); // Проверка наличия позиции $cart->has($product, $options); // Удаление позиции $cart->remove($product, $options); // Поиск позиции $position = $cart->find($product, $options); // Все позиции $cart->all(); // Очистка $cart->clear(); // Добавление количества $cart->setQuantity($key, 5); // Изменение количества $cart->setQuantity($key, 5, true); // Изменение количества - альтернативный вариант $position = $cart->get($key); $position->setQuantity($position->getQuantity() + 2); $cart->replace($key, $position);