irice/yii2-cart

Yii2 购物车

维护者

详细信息

github.com/iridance/yii2-cart

源代码

安装: 110

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 46

类型:yii2-extension

1.4 2018-08-20 20:01 UTC

This package is auto-updated.

Last update: 2024-09-04 14:08:59 UTC


README

Yii2 购物车扩展


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

Latest Stable Version Total Downloads License Build Status Scrutinizer Code Quality

支持我们

您的业务依赖于我们的贡献吗?通过 Patreon 联系我们并支持我们。所有承诺将致力于维护工作和开发新功能。

安装

安装此扩展的最佳方式是通过 composer

运行以下命令

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

或者

"yii2mod/yii2-cart": "*"

将以下内容添加到您的 composer.json 文件的 require 部分。

配置

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

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

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

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

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

php yii migrate --migrationPath=@vendor/yii2mod/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 \yii2mod\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);