PHPackages                             sieulog/yii2-shopping-cart - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. sieulog/yii2-shopping-cart

ActiveYii2-extension[Framework](/categories/framework)

sieulog/yii2-shopping-cart
==========================

Yii2 extension that adds shopping cart functions

1.2.2(10y ago)07PHPPHP &gt;=5.4.0

Since Oct 19Pushed 10y ago1 watchersCompare

[ Source](https://github.com/sieulog/yii2-shopping-cart)[ Packagist](https://packagist.org/packages/sieulog/yii2-shopping-cart)[ RSS](/packages/sieulog-yii2-shopping-cart/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (1)Versions (9)Used By (0)

Shopping cart for Yii 2
=======================

[](#shopping-cart-for-yii-2)

This extension adds shopping cart for Yii framework 2.0

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist omnilight/yii2-shopping-cart "*"

```

or add

```
"omnilight/yii2-shopping-cart": "*"
```

to the `require` section of your composer.json.

How to use
----------

[](#how-to-use)

In your model:

```
class Product extends ActiveRecord implements CartPositionInterface
{
    use CartPositionTrait;

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

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

In your controller:

```
public function actionAddToCart($id)
{
    $cart = new ShoppingCart();

    $model = Product::findOne($id);
    if ($model) {
        $cart->put($model, 1);
        return $this->redirect(['cart-view']);
    }
    throw new NotFoundHttpException();
}
```

Also you can use cart as global application component:

```
[
    'components' => [
        'cart' => [
            'class' => 'yz\shoppingcart\ShoppingCart',
            'cartId' => 'my_application_cart',
        ]
    ]
]
```

And use it in the following way:

```
\Yii::$app->cart->put($cartPosition, 1);
```

In order to get number of items in the cart:

```
$itemsCount = \Yii::$app->cart->getCount();
```

In order to get total cost of items in the cart:

```
$total = \Yii::$app->cart->getCost();
```

If the original model that you want to use as cart position is too heavy to be stored in the session, you can create a separate class implementing CartPositionInterface, and original model can implement CartPositionProviderInterface:

```
// app\models\Product.php

class Product extends ActiveRecord implements CartPositionProviderInterface
{
    public function getCartPosition()
    {
        return \Yii::createObject([
            'class' => 'app\models\ProductCartPosition',
            'id' => $this->id,
        ]);
    }
}

// app\models\ProductCartPosition.php

class ProductCartPosition extends Object implements CartPositionInterface
{
    /**
     * @var Product
     */
    protected $_product;

    public $id;

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

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

    /**
     * @return Product
    */
    public function getProduct()
    {
        if ($this->_product === null) {
            $this->_product = Product::findOne($this->id);
        }
        return $this->_product;
    }
}
```

This way gives us ability to create separate cart positions for the same product, that differs only on some property, for example price or color:

```
// app\models\ProductCartPosition.php

class ProductCartPosition extends Object implements CartPositionInterface
{
    public $id;
    public $price;
    public $color;

    //...
    public function getId()
    {
        return md5(serialize([$this->id, $this->price, $this->color]));
    }

    //...
}
```

Using discounts
---------------

[](#using-discounts)

Discounts are implemented as behaviors that could attached to the cart or it's positions. To use them, follow this steps:

1. Define discount class as a subclass of yz\\shoppingcart\\DiscountBehavior

```
// app/components/MyDiscount.php

class MyDiscount extends DiscountBehavior
{
    /**
     * @param CostCalculationEvent $event
     */
    public function onCostCalculation($event)
    {
        // Some discount logic, for example
        $event->discountValue = 100;
    }
}
```

2. Add this behavior to the cart:

```
$cart->attachBehavior('myDiscount', ['class' => 'app\components\MyDiscount']);
```

If discount is suitable not for the whole cart, but for the individual positions, than it is possible to attach discount to the cart position itself:

```
$cart->getPositionById($positionId)->attachBehavior('myDiscount', ['class' => 'app\components\MyDiscount']);

```

Note, that the same behavior could be used for both cart and position classes.

3. To get total cost with discount applied:

```
$total = \Yii::$app->cart->getCost(true);
```

4. During the calculation the following events are triggered:

- `ShoppingCart::EVENT_COST_CALCULATION` once per calculation.
- `CartPositionInterface::EVENT_COST_CALCULATION` for each position in the cart.

You can also subscribe on this events to perform discount calculation:

```
$cart->on(ShoppingCart::EVENT_COST_CALCULATION, function ($event) {
    $event->discountValue = 100;
});
```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 84.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~46 days

Recently: every ~70 days

Total

8

Last Release

3899d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/64c9b7bff910026717f970d45573371debb65a8ff5972260b4475158dddce619?d=identicon)[sieulog](/maintainers/sieulog)

---

Top Contributors

[![omnilight](https://avatars.githubusercontent.com/u/3306537?v=4)](https://github.com/omnilight "omnilight (38 commits)")[![OmgDef](https://avatars.githubusercontent.com/u/6762337?v=4)](https://github.com/OmgDef "OmgDef (3 commits)")[![damiandennis](https://avatars.githubusercontent.com/u/1276622?v=4)](https://github.com/damiandennis "damiandennis (2 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (1 commits)")[![sieulog](https://avatars.githubusercontent.com/u/14790712?v=4)](https://github.com/sieulog "sieulog (1 commits)")

---

Tags

yiishopping cart

### Embed Badge

![Health badge](/badges/sieulog-yii2-shopping-cart/health.svg)

```
[![Health](https://phpackages.com/badges/sieulog-yii2-shopping-cart/health.svg)](https://phpackages.com/packages/sieulog-yii2-shopping-cart)
```

###  Alternatives

[yiisoft/yii2-queue

Yii2 Queue Extension which supports queues based on DB, Redis, RabbitMQ, Beanstalk, SQS, and Gearman

1.1k10.4M155](/packages/yiisoft-yii2-queue)[omnilight/yii2-shopping-cart

Yii2 extension that adds shopping cart functions

221110.9k4](/packages/omnilight-yii2-shopping-cart)[omnilight/yii2-scheduling

Scheduling extension for Yii2 framework

3181.0M7](/packages/omnilight-yii2-scheduling)[skeeks/yii2-assets-auto-compress

Automatically compile and merge files js + css + html in yii2 project

162437.6k6](/packages/skeeks-yii2-assets-auto-compress)[iiifx-production/yii2-autocomplete-helper

Yii2 Autocomplete Helper

4226.9k2](/packages/iiifx-production-yii2-autocomplete-helper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
