mindy/cart

Shopping Cart component

2.2.1 2018-02-22 12:34 UTC

This package is not auto-updated.

Last update: 2024-04-28 02:37:52 UTC


README

Build Status codecov Latest Stable Version Total Downloads FOSSA Status

Установка

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);

License

FOSSA Status