yii2mod/yii2-cart

Yii2 购物车

安装次数: 15,085

依赖项: 1

建议者: 0

安全: 0

星标: 119

关注者: 29

分支: 46

开放问题: 9

类型:yii2-extension

1.4 2018-08-20 20:01 UTC

This package is auto-updated.

Last update: 2024-08-29 04:32:07 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;
    }
}

如果您使用 yii2mod\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);