riesenia/cart

提供购物车功能的 PHP 库

v4.1.1 2022-07-01 15:36 UTC

README

Build Status Latest Version Total Downloads Software License

提供基本购物车功能的 PHP 库。

安装

使用 composer require riesenia/cart 安装最新版本

或将它添加到您的 composer.json 文件中作为依赖项

{
    "require": {
        "riesenia/cart": "~4.0"
    }
}

注意:如果您使用 PHP 5.4 - 5.6,请使用此库的 1.* 版本。

使用方法

构造函数接受三个配置参数

  • 传递给每个添加的购物车项的上下文数据(您可以通过传递客户 ID 来解决自定义价格等)
  • 当列出含税价格时为 true,列出不含税价格时为 false(参见 详细说明
  • 四舍五入的小数位数

它们都可以单独设置。

use Riesenia\Cart\Cart;

// default is ([], true, 2)
$cart = new Cart();

$cart->setContext(['customer_id' => $_SESSION['customer_id']]);
$cart->setPricesWithVat(false);
$cart->setRoundingDecimals(4);

操作购物车项

可以通过购物车 ID(由 getCartId 方法提供)访问项。

// adding item to cart ($product has to implement CartItemInterface)
$cart->addItem($product);

// set quantity of the item when adding to cart
$cart->addItem($anotherProduct, 3);

// when $product->getCartId() returns i.e. 'abc'
$cart->setItemQuantity('abc', 7);

// remove item
$cart->removeItem('abc');

批量操作购物车项

可以使用 clear() 方法清空购物车。可以使用 setItems() 方法设置项。请注意,setItems 将首先调用 clear。所有添加的项都必须实现 CartItemInterface

获取项

可以使用 getItems 获取项。它接受 callable 或字符串(参见 getTotal 的示例)来过滤结果。

总计计算

购物车与 Decimal 类(参见 litipk/php-bignumbers)一起工作。您可以访问小计(不含增值税)、税项(所有税率的金额数组)和总计(小计加税项)。

// item 1 [price: 1.00, tax rate: 10]
// item 2 [price: 2.00, tax rate: 20]

// 3.00
echo $cart->getSubtotal();

// 0.10
echo $cart->getTaxes()[10];

// 0.40
echo $cart->getTaxes()[20];

// 3.50
echo $cart->getTotal();

按类型计算总计

// get totals of type 'product'
echo $cart->getTotal('product');

// get totals of type 'product' and 'service'
echo $cart->getTotal('product,service');

// get totals of all items except type 'product' and 'service'
echo $cart->getTotal('~product,service');

计算项价格

您可以使用 getItemPrice 方法获取项的价格。它会在计算价格之前设置购物车上下文,但您也可以修改参数来获取不含增值税的价格。

$cart = new Cart();
$cart->addItem($product, 3);

// get unit price without VAT
echo $cart->getItemPrice($product, 1, false);

获取购物车重量

实现 WeightedCartItemInterface 的项可以添加到购物车,因此购物车可以计算总重量。重量可以使用与计算总计相同的格式按类型计算。

// get weight of type 'product'
echo $cart->getWeight('product');

总计四舍五入

可以使用 setTotalRounding 方法设置四舍五入函数。这仅影响购物车的总计金额。可以通过 getRoundingAmount 方法访问四舍五入金额。

绑定购物车项

实现 BoundCartItemInterface 的项可以添加到购物车。当目标项从购物车中移除时,绑定项也会自动移除。如果 updateCartQuantityAutomatically 方法返回 true,绑定项也会反映目标项的数量的变化。

多个绑定购物车项

实现 MultipleBoundCartItemInterface 的项可以添加到购物车。当任何目标项从购物车中移除时,绑定项也会自动移除。

促销

您可以使用 setPromotions 方法设置促销。每个促销都必须实现 PromotionInterface。请注意,即使促销不符合条件,也会始终调用 beforeApplyafterApply 回调。只有当促销通过 isEligible 测试时,才会调用 apply 方法。

测试

您可以使用以下命令运行单元测试:

cd path/to/riesenia/cart
composer install
vendor/bin/phpspec run