Skip to content

Instantly share code, notes, and snippets.

@agungsijawir
Forked from petrabarus/Cart.php
Created January 24, 2016 17:46
Show Gist options
  • Save agungsijawir/053fb5789e50661d449f to your computer and use it in GitHub Desktop.
Save agungsijawir/053fb5789e50661d449f to your computer and use it in GitHub Desktop.
<?php
class Cart extends \yii\base\Object {
/**
* @var integer
*/
public $id;
/**
* @var Item[]
*/
public $items = [];
/**
* @var integer
*/
public $userId;
/**
* @var string
*/
public $sessionId;
/**
* @return Storage
*/
public static function getStorage() {
return Yii::$app->cartStorage;
}
/**
* @return static
*/
public static function load($id) {
return static::getStorage()->load($id);
}
/**
* @return boolean
*/
public function save() {
return static::getStorage()->store($this);
}
/**
* @return integer
*/
public function getItemQuantity() {
return array_sum(array_map(function(Item $item) {
return $item->quantity;
}, $this->items));
//Or array_sum(\yii\helpers\ArrayHelper::getColumn($this->items, 'quantity'));
}
public function isEmpty() {
return count($this->items) == 0;
}
public function getTotalPrice($withDiscount = true) {
return array_sum(array_map(function(Item $item) use ($withDiscount) {
return $item->quantity * $item->price * ($withDiscount ? $item->discount : 1);
}, $this->items;));
}
}
<?php
class DbStorage extends Storage {
/**
*@param array|\yii\db\Connection
*/
public $db = 'db';
public $table = 'Carts';
public function init() {
$this->db = \yii\di\Instance::ensure($this->db, \yii\db\Connection::class);
}
public function store(Cart $cart) {
//store in database
}
public function load($id) {
//load from database
}
}
<?php
class Item extends \yii\base\Object {
public $price;
public $quantity;
public $discount;
}
<?php
class SessionStorage extends Storage {
public function store(Cart $cart) {
//store in database
}
public function load($id) {
//load from database
}
}
<?php
abstract class Storage extends \yii\base\Object {
/**
* @return boolean
*
*/
abstract public function store(Cart $cart);
/**
* @return Cart
*/
abstract public function load($id);
/**
* @return string
*/
public static function serialize(Cart $cart) {
return serialize(['items' => $cart->items]);
}
/**
* @return Cart
*/
public static function unserialize($object) {
return new Cart(unserialize($object));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment