dev-master
9999999-devYii2 Shopping cart
MIT
The Requires
The Development Requires
by Igor Chepurnoy
1.3
1.3.0.0Yii2 Shopping cart
MIT
The Requires
The Development Requires
by Igor Chepurnoy
Yii2 Shopping cart
This extension adds shopping cart for Yii framework 2.0, (*1)
The preferred way to install this extension is through composer., (*3)
Either run, (*4)
php composer.phar require --prefer-dist yii2mod/yii2-cart "*"
or add, (*5)
"yii2mod/yii2-cart": "*"
to the require section of your composer.json
file., (*6)
1) Configure the cart
component:, (*7)
return [ //.... 'components' => [ 'cart' => [ 'class' => 'yii2mod\cart\Cart', // you can change default storage class as following: 'storageClass' => [ 'class' => 'yii2mod\cart\storage\DatabaseStorage', // you can also override some properties 'deleteIfEmpty' => true ] ], ] ];
2) Create the Product Model that implements an CartItemInterface
:, (*8)
class ProductModel extends ActiveRecord implements CartItemInterface { public function getPrice() { return $this->price; } public function getLabel() { return $this->name; } public function getUniqueId() { return $this->id; } }
If you use the yii2mod\cart\storage\DatabaseStorage as
storageClass
then you need to apply the following migration:, (*9)
php yii migrate --migrationPath=@vendor/yii2mod/yii2-cart/migrations
Operations with the shopping cart are very straightforward when using a models that implement one of the two cart interfaces.
The cart object can be accessed under \Yii::$app->cart
and can be overridden in configuration if you need to customize it., (*10)
// access the cart from "cart" subcomponent $cart = \Yii::$app->cart; // Product is an AR model implementing CartProductInterface $product = Product::findOne(1); // add an item to the cart $cart->add($product); // returns the sum of all 'vat' attributes (or return values of getVat()) from all models in the cart. $totalVat = $cart->getAttributeTotal('vat'); // clear the cart $cart->clear();
You can use the CartGrid
widget for generate table with cart items as following:, (*11)
[ 'id', 'label', 'price' ] ]); ?>
Products/items that are added to the cart are serialized/unserialized when saving and loading data from cart storage. If you are using Active Record models as products/discounts, make sure that you are omitting any unnecessary references from the serialized data to keep it compact., (*12)
// get all items from the cart $items = $cart->getItems(); // get only products $items = $cart->getItems(Cart::ITEM_PRODUCT); // loop through cart items foreach ($items as $item) { // access any attribute/method from the model var_dump($item->getAttributes()); // remove an item from the cart by its ID $cart->remove($item->uniqueId) }
Yii2 Shopping cart
MIT
Yii2 Shopping cart
MIT