PHP code example of cdev38399 / yii2-shopping-cart-private
1. Go to this page and download the library: Download cdev38399/yii2-shopping-cart-private 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/ */
cdev38399 / yii2-shopping-cart-private 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();
}
// 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;
}
}