PHP code example of weison-tech / yii2-shopping-cart

1. Go to this page and download the library: Download weison-tech/yii2-shopping-cart library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

weison-tech / yii2-shopping-cart example snippets


class Product extends ActiveRecord implements CartPositionInterface
{
    use CartPositionTrait;

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

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

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();
}

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

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

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

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

// 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;
    }
}

// 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]));
    }

    //...
}

// app/components/MyDiscount.php

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

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

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

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

php composer.phar