1. Go to this page and download the library: Download vsevolod-ryzhov/yii2-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/ */
vsevolod-ryzhov / yii2-cart example snippets
// setup Cart component using apInterface
{
public function bootstrap($app): void
{
$container = Yii::$container;
$container->setSingleton(Cart::class, [], [
new SessionStorage('cart', $app->session), new BaseCost()
]);
}
}
// Product class must implement ProductInterface
class Product implements ProductInterface
{
public function getId()
{
return $this->id;
}
public function getPrice()
{
return $this->price;
}
}
// inject component in your controller
class CartController extends Controller
{
/**
* @var Cart
*/
private $cart;
public function __construct($id, $module, Cart $cart, $config = [])
{
parent::__construct($id, $module, $config);
$this->cart = $cart;
}
public function actionAdd($id, $count = 1)
{
$product = Product::findOne($id);
$this->cart->add($product, $count);
}
}
// create converter class which extends model class to CartItem class
// this class is used in Init class on DatabaseStorage initialization
class ProductToCartConverter extends AbstractProductConverter
{
public function convertProductToCartItem($product, int $quantity): CartItem
{
/* @var $product Product */
return new CartItem($product, $quantity);
}
}
// setup Cart component using le & etc)
$container->setSingleton(Cart::class, [], [
new DatabaseStorage($app->user->id, $app->db, new ProductsQuery(Product::class), new ProductToCartConverter), new BaseCost()
]);
}
}
}
// Query class for Product model must extends
// use ProductToCartConverter from previews sample
class Init implements BootstrapInterface
{
$container->setSingleton(Cart::class, [], [
new CookieStorage(
new CookieStorageSettings('cart', 3600),
$app->request->cookies,
$app->response->cookies,
new ProductsQuery(Product::class),
new ProductToCartConverter
),
new BaseCost()
]);
}
class Init implements BootstrapInterface
{
public function bootstrap($app): void
{
$container = Yii::$container;
$container->setSingleton(Cart::class, [], [
new CombinedStorage(
$app->user,
$app->db,
new CookieStorageSettings('cart', 3600),
$app->request->cookies,
$app->response->cookies,
new ProductsQuery(Product::class),
new ProductToCartConverter
),
new BaseCost()
]);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.