PHP code example of omnilight / yii2-shopping-cart
1. Go to this page and download the library: Download omnilight/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/ */
omnilight / 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 = Yii::$app->cart;
$model = Product::findOne($id);
if ($model) {
$cart->put($model, 1);
return $this->redirect(['cart-view']);
}
throw new NotFoundHttpException();
}
// 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;
}
}