crocone/yii2-cart

Yii2 购物车

维护者

详细信息

github.com/crocone/yii2-cart

源代码

安装: 13

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 46

类型:yii2-extension

1.4.3.6 2020-01-06 00:16 UTC

README

Yii2 购物车扩展


此扩展为 Yii 2.0 框架添加购物车功能。

Latest Stable Version Total Downloads License Build Status Scrutinizer Code Quality

安装

安装此扩展的首选方式是通过 composer

运行以下命令:

php composer.phar require --prefer-dist crocone/yii2-cart "*"

或者将以下内容添加到你的 composer.json 文件的 require 部分:

"crocone/yii2-cart": "*"

配置

  1. 配置 cart 组件
return [
    //....
    'components' => [
        'cart' => [
            'class' => 'crocone\cart\Cart',
            // you can change default storage class as following:
            'storageClass' => [
                'class' => 'crocone\cart\storage\DatabaseStorage',
                // you can also override some properties 
                'deleteIfEmpty' => true
            ]
        ],
    ]
];
  1. 创建实现 CartItemInterface 的 Product 模型
class ProductModel extends ActiveRecord implements CartItemInterface
{

    public function getPrice()
    {
        return $this->price;
    }

    public function getLabel()
    {
        return $this->name;
    }

    public function getUniqueId()
    {
        return $this->id;
    }
}

如果你使用 crocone\cart\storage\DatabaseStorage 作为 storageClass,则需要应用以下迁移:

php yii migrate --migrationPath=@vendor/crocone/yii2-cart/migrations

使用购物车

当使用实现两种购物车接口之一的模型时,购物车的操作非常简单。可以通过 \Yii::$app->cart 访问购物车对象,并且可以在配置中覆盖它以进行自定义。

// access the cart from "cart" subcomponent
$cart = \Yii::$app->cart;

// Product is an AR model implementing CartProductInterface
$product = Product::findOne(1);

// add an item to the cart
$cart->add($product);

// returns the sum of all 'vat' attributes (or return values of getVat()) from all models in the cart.
$totalVat = $cart->getAttributeTotal('vat');

// clear the cart
$cart->clear();

查看购物车商品

你可以使用 CartGrid 小部件来生成以下表格,其中包含购物车商品:

<?php echo \crocone\cart\widgets\CartGrid::widget([
    // Some widget property maybe need to change. 
    'cartColumns' => [
        'id',
        'label',
        'price'
    ]
]); ?>

购物车中的商品

添加到购物车的产品/商品在保存和从购物车存储加载数据时会被序列化/反序列化。如果你使用 Active Record 模型作为产品/折扣,请确保你从序列化数据中省略任何不必要的引用,以保持其紧凑。

// get all items from the cart
$items = $cart->getItems();

// get only products
$items = $cart->getItems(Cart::ITEM_PRODUCT);

// loop through cart items
foreach ($items as $item) {
    // access any attribute/method from the model
    var_dump($item->getAttributes());

    // remove an item from the cart by its ID
    $cart->remove($item->uniqueId)
}

获取购物车中产品数量

你可以使用 getCount 来获取数量,如下例所示:

// get count of all products in cart:
$items = $cart->getCount();

// get count of Specific Item Type:
$items = $cart->getCount(Cart::ITEM_PRODUCT);