The code:
SessionInterface
SessionManager
SessionUser
SessionCart
ServiceCart
SessionManager uses yii2 session interface to interact together:
code
interface SessionInterface
{
public function getId(): string;
public function set(string $key, $value): void;
public function get(string $key);
public function has(string $key): bool;
public function remove(string $key): void;
public function destroy(): void;
public function isActive(): bool;
}
class SessionManager implements SessionInterface
{
public function getId(): string
{
$this->validateSession();// Ensure the session is open.
return \Yii::$app->session->getId();
}
public function set(string $key, $value): void
{
$this->validateSession();// Ensure the session is open.
\Yii::$app->session->set($key, $value);
}
public function get(string $key)
{
$this->validateSession();// Ensure the session is open.
return \Yii::$app->session->get($key);
}
public function has(string $key): bool
{
$this->validateSession();// Ensure the session is open.
return \Yii::$app->session->has($key);
}
public function remove(string $key): void
{
$this->validateSession();// Ensure the session is open.
\Yii::$app->session->remove($key);
}
public function destroy(): void
{
$this->validateSession();// Ensure the session is open.
\Yii::$app->session->destroy();
}
public function isActive(): bool
{
return \Yii::$app->session->isActive;
}
private function validateSession(): void
{
if (!$this->isActive())
{
\Yii::$app->session->open();
}
}
}
SessionUser is a ActiveRecorder model that "SessionUser represents a user session stored in DB with enhanced security features."
Here is the write up on it:
code
/**
* @property int $id
* @property string $session_id
* @property string|null $session_token
* @property string|null $user_ip
* @property string|null $user_agent
* @property int $created_at
* @property int|null $updated_at
* @property string|null $extra_data
*
* If you want to avoid creating a new SessionManager instance every time, you could also
* bootstrap the dependency through the Yii application component:
*
* First, register your SessionManager component in your application
* configuration (usually in config/web.php or config/console.php):
*
* 'components' => [
* 'sessionManager' => [
* 'class' => 'app\components\SessionManager',
* ],
* 'sessionUser' => [
* 'class' => \app\models\SessionUser::class,
* 'sessionManager' => \Yii::$app->sessionManager,// inject existing component
* ],
* ],
*
* This way, you can get the session user anywhere via:
*
* $sessionUser = \Yii::$app->sessionUser;
*
* Use a base controller that all your controllers extend:
*
* namespace app\controllers;
*
* use yii\web\Controller;
* use app\components\SessionManager;
* use app\models\SessionUser;
*
* class BaseController extends Controller
* {
* protected SessionUser $_sessionUser;
*
* public function init()
* {
* parent::init();// __construct()
*
* $sessionManager = new SessionManager();
* $this->_sessionUser = new SessionUser($sessionManager);
*
* // Optionally, do initial session validation/load here
* }
* }
*
* public function beforeAction($action)
* {
* if (parent::beforeAction($action))
* {
*
* $sessionData = null;
* try
* {
* $sessionData = $this->_sessionUser->readSession();
* }
* catch (\Throwable $e)
* {
* \Yii::error('Error reading session data: ' . $e->getMessage());
* }
* if (!$sessionData)
* {
* $this->_sessionUser->writeSession([
* 'extra_data' => ['order_id' => '123'],
* // additional default values if needed...
* ]);
* }
* return true;
* }
* // If parent::beforeAction returns false, deny access.
* return false;
* }
*
* Usage example to read session:
*
* $sessionUser = new SessionUser();
* $data = $sessionUser->readSession();
* if ($data === null)
* {
* // Session invalid — user should reauthenticate or session cleared
* }
*/
SessionUser works well and needs no changes. SessionCart and ServiceCart are the goal today.
SessionCart writeup:
code
Assistant
Your observation is correct: as it stands, getCartItems() returns the raw cart data from the session user without validating or enriching the information based on current inventory and product info.
Since your checkInventory() method basically does the following:
Takes the current cart items,
Validates the existence and status of the product,
Updates quantities if stock is insufficient,
Enriches items with price, title, total price, available quantity,
And then saves the updated cart data back to session,
it would definitely make sense for getCartItems() to return the cleaned and enriched cart state by delegating to checkInventory().
Suggested change
Modify getCartItems() so it calls and returns the result of checkInventory() like:
php
public function getCartItems(): array
{
return $this->checkInventory();
}
This ensures whenever you retrieve cart items, you get valid, up-to-date data with price and availability, and the session cart is synchronized with the real state.
Why this is good:
Data consistency: Cart quantities and prices are always validated against actual products; no stale data.
Cleaner API: Consumers of SessionCart don’t have to know to call an explicit inventory check first.
Automatic correction: Any invalid or out-of-stock items removed or fixed transparently on read.
Session state updated: The adjusted cart data is persisted back to the session, avoiding discrepancies.
Minor considerations
Frequent calls to getCartItems() will trigger DB queries (Product::find()...), so cache or optimize queries if performance becomes an issue.
If some use cases want raw cart data (e.g., internal debugging), consider adding a separate getRawCartItems() method.
Ensure your writeSession() method in SessionUser handles concurrency well so no updates get lost.
Summary
Your intent to have getCartItems() invoke checkInventory() is a good design practice here:
php
public function getCartItems(): array
{
return $this->checkInventory();
}
This will make the cart operations more robust, secure, and user-friendly.
User
maybe we could refactor:
code
public function getCartItems(): array
{
$this->checkInventory();
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null)
{
return [];
}
return $sessionData['cart_data'] ?? [];
}
how would you optimize the entire code of SessionCart?
Assistant
Thanks for the follow-up! Your idea to avoid redundant calls and optimize the flow makes sense: you want to ensure that you only call checkInventory() when necessary, but also avoid multiple DB calls and session writes in repeated calls to getCartItems() within the same request or same instance lifecycle.
Goal: Efficient, consistent cart item retrieval where inventory is validated/updated only once per request
Problem with current approach
Every call to getCartItems() calls checkInventory()
checkInventory() reads session + queries DB + potentially writes back to session
Multiple calls in one request could cause repeated DB queries and session writes (expensive)
Refactor approach: cache internally the checked cart items
Add a private property to hold the current cart items after inventory check:
php
private ?array $_cartItemsCache = null;
Then, refactor getCartItems() so:
php
public function getCartItems(): array
{
// If cached, just return it
if ($this->_cartItemsCache !== null) {
return $this->_cartItemsCache;
}
// If no session or cart_data, return empty array immediately
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null) {
return [];
}
// If no cart data, nothing to check
if (empty($sessionData['cart_data'])) {
$this->_cartItemsCache = [];
return $this->_cartItemsCache;
}
// Otherwise, validate inventory and update session/cart items cache
$this->_cartItemsCache = $this->checkInventory();
return $this->_cartItemsCache;
}
Adjust checkInventory() to:
Use the current cached cart items if set (optional)
Return the updated cart items as before
User
are we using yii2 cache for this? than should we not set a timeframe? what if a item sells? during that time..
Assistant
Good question!
Are we using Yii2 cache for this?
No, the above _cartItemsCache is an in-memory, per-object (per PHP request) private property cache, NOT a persisted cache like Yii2 Cache component (file, Redis, memcached, etc.).
That means:
The cached cart data only lives during this single PHP request,
It is cleared automatically at the end of the request,
And there is no risk of stale data persisting across requests,
So you don't need expiration times or invalidation logic related to time.
Why this is safe in terms of timings and inventory changes?
Inventory is checked fresh on each request's (likely first) call to getCartItems().
If a product sells out between requests, your next PHP request (new user page load or AJAX call) will call checkInventory() again, get correct updated quantities & reflect out-of-stock or adjusted quantities.
So inventory info is always current to the request lifecycle.
When would Yii2 Cache or other persistent caching help?
Using Yii2 Cache with a duration to cache cart data or product inventory info could help if:
You want to optimize DB queries by caching product data for short periods (e.g., 10 seconds, 30 seconds),
And are okay with some small lag in reflecting inventory changes (which is often acceptable in e-commerce),
Or you want to cache expensive calculations or results shared across users.
In that case, you would:
Wrap product lookups in cached getters,
Store inventory data or product info in Yii2 Cache with time-to-live (TTL),
Possibly refresh cache or invalidate on stock changes.
But cart data itself?
Cart data is user session-specific and dynamic, so caching at the session level is less common.
You want to avoid stale state for users, especially for quantities/prices.
Per-request in-memory cache is enough to optimize repeated method calls in the same request.
Summary & recommendations:
Aspect
Current design (in-memory cache)
Persistent Yii2 Cache
User
This is the CartService
code
Assistant
Thanks for sharing your CartService code! You've done a solid job of creating a service that manages persistent carts for authenticated users, complementing your SessionCart that manages session-based carts for guests.
Here’s some detailed feedback and suggestions on aligning CartService and SessionCart in design and functionality, to keep them roughly equivalent but suitable for their different storage backends:
1) Overall Architecture Alignment
SessionCart manages array data in user session through SessionUser.
CartService manages persistent DB records (Cart ActiveRecord) for a logged-in user.
Your design goal—to provide same kind of cart API/operations abstracted behind these two backends—is good and a common pattern (session cart vs user cart).
2) Functionality Correspondence
SessionCart method
CartService equivalent
Notes/Points for alignment
getCartItems()
getCartItems()
Both check inventory and return enriched cart items.
addItem(productId, qty)
addItem(productId, qty, $new)
Both add or update item quantities.
removeItem(productId)
removeItem(productId)
Remove item from cart.
clearCart()
clearCart()
Clear full cart.
getCartQuantity()
getCartQuantity()
Return total item count in cart.
getCartTotal()
getCartTotal()
Return total price for the cart contents.
3) Detailed Suggestions
A) Naming consistency:
CartService::addItem has a $new boolean to decide if it should create new or not; SessionCart::addItem just adds or increments implicitly.
Consider normalizing so both just add, and maybe have a separate method if you want "strict" insert or update treatment.
User
"
code
CartService::addItem has a $new boolean to decide if it should create new or not; SessionCart::addItem just adds or increments implicitly.
Consider normalizing so both just add, and maybe have a separate method if you want "strict" insert or update treatment.
"
For now this is fine. might change the word $new, since its tad confusing.. but it meant for "adding new product" into the cart activeRecord.
"CartService::getNavbarCartQuantity() is a nice helper for UI.
code
You might add similar for session cart.
"
Yes, need todo this.
"aching/Reducing DB Hits in CartService
code
You're Product querying again in updateCartQuantity() inside addItem(), which could be optimized by caching the product fetched in checkInventory() or passed in parameters.
When calculating total price on getCartTotal(), you're doing
Optimization: eager load products in getCartItems() and use $item->product->price.
"
Help refactor the code to be more optimized.
"E) Return types and nullability:
code
getCartQuantity() returns int, but SessionCart returns ?int.
Consider aligning to either return 0 or null if empty.
You might unify either way but be consistent.
"
What do you think is best?
"F) In CartService::removeItem(), if item does not exist, no return statement (implicit null).
code
Consider adding explicit return false for clarity.
"
Lets do this
Assistant
Thanks for your follow-ups! Below are the concrete code refactors and recommendations based on your points.
1) Rename $new parameter in addItem() in CartService
Instead of $new, use a more descriptive parameter name, eg:
php
public function addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
{
// ...
if ($cart === null) {
if (!$createIfNotExists) {
return false;
}
// Create new Cart record
}
// ...
}
2) Add similar getNavbarCartQuantity() helper for SessionCart
Add to SessionCart:
php
public function getNavbarCartQuantity(): ?int
{
return $this->getCartQuantity(); // Assuming getCartQuantity() returns ?int already
}
3) Refactor CartService to avoid redundant Product queries and eager load products properly
Refactor getCartItems() to eager load products once:
php
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()
->with('product') // eager load products
->where(['created_by' => $this->_userId])
->all();
}
Refactor getCartTotal() to use eager loaded products, preventing N+1 queries:
php
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item)
{
// Use eager loaded product, fallback to 0 if no product
$price = $item->product->price ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
User
can you send the complete code for CartService that you refactored
Assistant
Certainly! Below is the refactored complete CartService incorporating the discussed improvements:
Renamed $new parameter to $createIfNotExists
Eager loading of product relation in getCartItems()
Avoid N+1 queries in getCartTotal() by using eager loaded product info
Accepting an optional Product parameter in updateCartQuantity() to reuse fetched product
Explicit return false in removeItem() when item not found
Logging preserved, plus minor cleanup
php
User
explain:
code
if ($product === null)
{
$product = $cart->product;
if ($product === null)
{
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
Assistant
Certainly! Here's a detailed explanation of this code snippet:
php
if ($product === null)
{
$product = $cart->product;
if ($product === null)
{
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
What it does — step by step:
Check if the $product parameter passed into the method is null:
The method updateCartQuantity() can accept a Product object as an optional parameter to avoid querying it again if already available.
If the caller did NOT supply a Product object ($product === null), the method must obtain it itself.
If $product is null, fetch the associated product record from the $cart record:
php
$product = $cart->product;
This uses the ActiveRecord relation product of the $cart item to get the associated Product instance.
This fetches the product from the database if it wasn’t eagerly loaded earlier.
If the product still cannot be found (possibly deleted from DB), log an error and bail out:
php
if ($product === null)
{
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
This means the cart item points to a product ID that no longer exists (or there was a DB error).
The code logs an error with details (product ID and method name) to help with debugging.
Since without a product you cannot enforce inventory or prices, the method returns indicating failure.
User
write clear and short comments for that code
Assistant
php
// If no product passed in, try to get it from the cart relation
if ($product === null)
{
$product = $cart->product;
// If product still not found, log error and abort update
if ($product === null)
{
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
User
namespace app\components;
use Yii;
use yii\db\Exception as YiiDbException;
use yii\helpers\ArrayHelper;
use app\models\Cart;
use app\models\Product;
use app\components\MoneyHelper;
use app\helpers\ExceptionLogger;
use app\helpers\LogHelper;
class CartService
{
private int $_userId;
code
Assistant
Certainly! Here is the refactored CartService class with a focus on improving checkInventory() and updateCartQuantity() methods, adding proper try-catch blocks around ActiveRecord save/delete operations to handle exceptions gracefully:
php
User
wouldnt this be correct:
code
if ($quantityProduct <= 0)
{
// Product out of stock - remove cart item
try
{
if (!$cartItem->delete())
{
new YiiDbException('Failed to delete cart item.');
}
continue;
}
catch (Throwable $e)
{
ExceptionLogger::log(
$e,
'cart_service_checkInventory_exception_',
$cartItem
);
}
}
Assistant
Almost — your intent is right to throw or handle the exception if deleting fails, but this code has a couple of issues:
php
if ($quantityProduct <= 0)
{
// Product out of stock - remove cart item
try
{
if (!$cartItem->delete())
{
new YiiDbException('Failed to delete cart item.');
}
continue;
}
catch (Throwable $e)
{
ExceptionLogger::log(
$e,
'cart_service_checkInventory_exception_',
$cartItem
);
}
}
What’s wrong:
new YiiDbException('...') by itself does nothing — You create an exception instance but do not throw it or handle it, so it’s effectively ignored.
continue is inside the try block after the delete — good, but if delete() returns false and you do nothing (except instantiate exception), the continue still runs, so the failure is silently ignored.
You want to throw or log on failure, but just creating an exception object doesn’t do either.
Correct approach
You have two options if delete() returns false:
Throw the exception so it goes to the catch
Or directly log an error without creating an exception
Example #1 — Throw exception:
php
if ($quantityProduct <= 0)
{
// Product out of stock - remove cart item
try
{
if (!$cartItem->delete())
{
throw new YiiDbException('Failed to delete cart item.');
}
continue;
}
catch (Throwable $e)
{
ExceptionLogger::log(
$e,
'cart_service_checkInventory_exception_',
$cartItem
);
}
}
User
can you help me now finish the CartController? this is what I have so far:
code
Assistant
Your CartController is progressing well! I’ve reviewed it and fixed some issues, added missing declarations, and completed some logic to make it functional and consistent. Here’s a refactored and complete version with comments:
Great question! Here's a straightforward implementation plan with sample code snippets for the rest of the actions in your CartController based on the HTTP verbs and typical e-commerce behavior.
1. actionDelete — Remove one product from cart
php
public function actionDelete(): \yii\web\Response
{
$request = \Yii::$app->request;
$productId = $request->post('productId');
if (!$productId) {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Invalid product.'));
return $this->redirect(['cart/index']);
}
$success = $this->_isGuest
? $this->_sessionCart->removeItem((int)$productId)
: $this->_cartService->removeItem((int)$productId);
if ($success) {
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Item removed from cart.'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Failed to remove item.'));
}
return $this->redirect(['cart/index']);
}
2. actionClear — Empty the entire cart
php
public function actionClear(): \yii\web\Response
{
$success = $this->_isGuest
? $this->_sessionCart->clearCart()
: $this->_cartService->clearCart();
if ($success) {
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Cart cleared successfully.'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Failed to clear cart.'));
}
return $this->redirect(['cart/index']);
}
3. actionPurchase — Start checkout, create order (simplified)
php
User
Would you like me to help build any related forms, models, or views next?
Yes
Assistant
Great! Here’s a roadmap for what you’ll commonly need next and a starter for each:
1. Forms
a) CartAddForm
Used for adding products to the cart via POST.
php
namespace app\models\forms;
use yii\base\Model;
class CartAddForm extends Model
{
public int $productId;
public int $quantity = 1;
public function rules(): array
{
return [
[['productId', 'quantity'], 'required'],
[['productId', 'quantity'], 'integer'],
['quantity', 'default', 'value' => 1],
['quantity', 'integer', 'min' => 1],
['productId', 'exist', 'targetClass' => \app\models\Product::class, 'targetAttribute' => 'id'],
];
}
}
b) CartUpdateForm
Used on the cart update page, to modify quantities of multiple items.
php
namespace app\models\forms;
use yii\base\Model;
class CartUpdateForm extends Model
{
public array $items = [];
public function rules(): array
{
return [
['items', 'each', 'rule' => [
'type' => 'array',
'rule' => [
[['productId', 'quantity'], 'required'],
[['productId', 'quantity'], 'integer'],
['quantity', 'integer', 'min' => 0], // quantity 0 means remove
['productId', 'exist', 'targetClass' => \app\models\Product::class, 'targetAttribute' => 'id'],
]
]],
];
}
}
Note: You might want to customize validation messages or transform from the form post accordingly.
User
"If you want, I can generate fully working form models with validation scenarios or build more polished views including product info display and AJAX features—just ask!"
ok great
Assistant
Sure! Let’s start by generating fully working form models with validation scenarios and then I’ll provide enhanced views with product info display and AJAX features for a better user experience.
1. Fully Working Form Models with Validation Scenarios
a) CartAddForm.php
php
namespace app\models\forms;
use yii\base\Model;
use app\models\Product;
class CartAddForm extends Model
{
public int $productId;
public int $quantity = 1;
public function rules(): array
{
return [
[['productId', 'quantity'], 'required'],
[['productId', 'quantity'], 'integer'],
['quantity', 'integer', 'min' => 1],
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => 'id'],
];
}
public function attributeLabels(): array
{
return [
'productId' => 'Product',
'quantity' => 'Quantity',
];
}
}
b) CartUpdateForm.php
php
namespace app\models\forms;
use yii\base\Model;
use app\models\Product;
class CartUpdateForm extends Model
{
/**
* @var array the submitted cart items structured as:
* [
* ['productId' => 1, 'quantity' => 2],
* ['productId' => 2, 'quantity' => 1],
* ]
*/
public array $items = [];
public function rules(): array
{
return [
['items', 'required'],
['items', 'each', 'rule' => [
'type' => 'array',
'rule' => [
[['productId', 'quantity'], 'required'],
[['productId', 'quantity'], 'integer'],
['quantity', 'integer', 'min' => 0], // quantity 0 means remove
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => 'id'],
],
]],
];
}
public function attributeLabels(): array
{
return [
'items' => 'Cart Items',
];
}
}
Not yet included in a published release.
/**
* SessionCart manages cart functionality by interacting with SessionUser's cart_data.
* It is a thin layer focused on cart operations while inheriting full session security.
*
* Usage:
*
* $sessionUser = new SessionUser();
* $sessionCart = new SessionCart($sessionUser);
*
* Add 3 units of product with id=101
*
* $success = $sessionCart->addProductToCart(101, 3);
*
* Fetch all items
*
* $items = $sessionCart->getCartItems();
*
* Get cart quantity and total
*
* $quantity = $sessionCart->getCartQuantity();
* $total = $sessionCart->getCartTotal();
*/
class SessionCart
{
private SessionUser $_sessionUser;
public function __construct(SessionUser $sessionUser)
{
$this->_sessionUser = $sessionUser;
}
public function getCartItems(): array
{
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null)
{
return [];
}
return $sessionData['cart_data'] ?? [];
}
private function checkInventory(): array
{
$items = $this->getCartItems();
if (empty($items))
{
return [];
}
foreach ($items as $index => &$item)
{
$productId = (int) ($item['id'] ?? 0);
if ($productId <= 0)
{
unset($items[$index]);
continue;
}
// @var Product|null $product
$product = Product::find()->id($productId)->published()->one();
if (!$product)
{
unset($items[$index]);
continue;
}
$availableQty = (int) $product->quantity;
// Adjust cart quantity if exceeds available stock
if (($item['quantity'] ?? 0) > $availableQty)
{
$item['quantity'] = $availableQty;
}
$item['available_quantity'] = $availableQty;
$item['price'] = (float) $product->price;
$item['title'] = $product->title;
$item['total_price'] = round($item['quantity'] * $item['price'], 2);
// Add any other product info you want here (e.g., image, slug)
}
unset($item);
// Optionally save adjusted quantities back to sessionUser
$this->_sessionUser->writeSession(['cart_data' => $items]);
return $items;
}
public function addItem(int $productId, int $quantity): bool
{
if ($quantity <= 0)
{
return false;
}
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null)
{
return false;
}
$cartData = $sessionData['cart_data'] ?? [];
$found = false;
foreach ($cartData as &$item)
{
if (($item['id'] ?? null) === $productId)
{
$item['quantity'] += $quantity;
$found = true;
break;
}
}
unset($item);
if (!$found)
{
$cartData[] = ['id' => $productId, 'quantity' => $quantity];
}
return $this->_sessionUser->writeSession(['cart_data' => $cartData]);
}
public function removeItem(int $productId): bool
{
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null)
{
return false;
}
$cartData = $sessionData['cart_data'] ?? [];
$originalCount = count($cartData);
// Remove all cart items matching the given product ID from the cart data array
$cartData = array_filter($cartData, fn($item) => ($item['id'] ?? null) !== $productId);
// product not found
if (count($cartData) === $originalCount)
{
return false;
}
return $this->_sessionUser->writeSession(['cart_data' => array_values($cartData)]);
}
public function clearCart(): bool
{
return $this->_sessionUser->writeSession(['cart_data' => []]);
}
public function getCartQuantity(): ?int
{
$items = $this->getCartItems();
if (empty($items))
{
return null;
}
$sum = 0;
foreach ($items as $item)
{
$sum += (int) ($item['quantity'] ?? 0);
}
return $sum > 0 ? $sum : null;
}
public function getCartTotal(): ?float
{
$items = $this->getCartItems();
if (empty($items))
{
return null;
}
$sum = 0.0;
foreach ($items as $item)
{
// If you've stored total_price per item, use it. Otherwise, integrate with product prices.
$sum += (float) ($item['total_price'] ?? 0);
}
return $sum > 0 ? round($sum, 2) : null;
}
}
When using getCartItems() it should first checkInventory() I wanted to make sure that this would work well. Thoughts?
Update session cart data as original does
Full optimized SessionCart for clarity:
php
class SessionCart
{
private SessionUser $_sessionUser;
private ?array $_cartItemsCache = null;
public function __construct(SessionUser $sessionUser)
{
$this->_sessionUser = $sessionUser;
}
public function getCartItems(): array
{
if ($this->_cartItemsCache !== null) {
return $this->_cartItemsCache;
}
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null) {
return [];
}
if (empty($sessionData['cart_data'])) {
$this->_cartItemsCache = [];
return $this->_cartItemsCache;
}
$this->_cartItemsCache = $this->checkInventory();
return $this->_cartItemsCache;
}
private function checkInventory(): array
{
$items = $this->_cartItemsCache ?? $this->_sessionUser->readSession()['cart_data'] ?? [];
if (empty($items)) {
return [];
}
foreach ($items as $index => &$item) {
$productId = (int) ($item['id'] ?? 0);
if ($productId <= 0) {
unset($items[$index]);
continue;
}
$product = Product::find()->id($productId)->published()->one();
if (!$product) {
unset($items[$index]);
continue;
}
$availableQty = (int) $product->quantity;
if (($item['quantity'] ?? 0) > $availableQty) {
$item['quantity'] = $availableQty;
}
$item['available_quantity'] = $availableQty;
$item['price'] = (float) $product->price;
$item['title'] = $product->title;
$item['total_price'] = round($item['quantity'] * $item['price'], 2);
}
unset($item);
// Update the cached cart items and persist session changes
$items = array_values($items);
$this->_cartItemsCache = $items;
$this->_sessionUser->writeSession(['cart_data' => $items]);
return $items;
}
public function addItem(int $productId, int $quantity): bool
{
if ($quantity <= 0) {
return false;
}
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null) {
return false;
}
$cartData = $sessionData['cart_data'] ?? [];
$found = false;
foreach ($cartData as &$item) {
if (($item['id'] ?? null) === $productId) {
$item['quantity'] += $quantity;
$found = true;
break;
}
}
unset($item);
if (!$found) {
$cartData[] = ['id' => $productId, 'quantity' => $quantity];
}
// Invalidate cache on mutations
$this->_cartItemsCache = null;
return $this->_sessionUser->writeSession(['cart_data' => $cartData]);
}
public function removeItem(int $productId): bool
{
$sessionData = $this->_sessionUser->readSession();
if ($sessionData === null) {
return false;
}
$cartData = $sessionData['cart_data'] ?? [];
$originalCount = count($cartData);
$cartData = array_filter($cartData, fn($item) => ($item['id'] ?? null) !== $productId);
if (count($cartData) === $originalCount) {
// product not found
return false;
}
$this->_cartItemsCache = null;
return $this->_sessionUser->writeSession(['cart_data' => array_values($cartData)]);
}
public function clearCart(): bool
{
$this->_cartItemsCache = null;
return $this->_sessionUser->writeSession(['cart_data' => []]);
}
public function getCartQuantity(): ?int
{
$items = $this->getCartItems();
if (empty($items)) {
return null;
}
$sum = 0;
foreach ($items as $item) {
$sum += (int) ($item['quantity'] ?? 0);
}
return $sum > 0 ? $sum : null;
}
public function getCartTotal(): ?float
{
$items = $this->getCartItems();
if (empty($items)) {
return null;
}
$sum = 0.0;
foreach ($items as $item) {
$sum += (float) ($item['total_price'] ?? 0);
}
return $sum > 0 ? round($sum, 2) : null;
}
}
Explanation & benefits:
Cache results: Prevent multiple DB calls & session writes within one request or one object instance.
Invalidate cache on mutations: Every add/remove/clear resets cache, so next read reflects new state.
Minimal duplication: We only read session/inventory once per request, but have clean, safe API.
If you want, you can later extend it with some optional cache invalidation logic based on timestamps or session events, but this should cover your use case nicely.
If you want me to help with testing or more features (e.g., discounts, taxes), just ask!
Cache lifespan
Only during current PHP request
Across requests, up to TTL / manual invalidation
Risk of stale inventory
No, always fresh per request
Possible if TTL too long, needs invalidation
When to use
For intra-request optimization
When optimizing DB or API calls across users
Complexity
Simple
Increased (cache keys, TTL, invalidation)
Conclusion for your use case
Stick with the current private property cache, it covers efficient usage without stale data risk.
If you notice DB bottlenecks/overload, consider caching product info separately with a short TTL using Yii2 cache.
Always keep the cart data saved and validated per user session — no persistent caching there.
If you want, I can help you extend SessionCart or Product repository to introduce Yii2 caching for product inventory with proper TTL and invalidation hooks. Just ask!
namespace app\components;
use Yii;
use yii\db\Exception as YiiDbException;
use yii\helpers\ArrayHelper;
use app\models\Cart;
use app\models\Product;
use app\components\MoneyHelper;
use app\helpers\ExceptionLogger;
use app\helpers\LogHelper;
class CartService
{
private int $_userId;
public function __construct(int $userId)
{
$this->_userId = $userId;
}
public function getNavbarCartQuantity(): int|null
{
$sum = Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity');
return $sum === null ? null : (int) $sum;
}
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()->where(['created_by' => $this->_userId])->all();
}
private function checkInventory(): void
{
// Get all cart items for this user with product eager loaded
$cartItems = self::find()
->alias('c')
->with('product')// eager load product relation
->where(['c.created_by' => $this->_userId])
->all();
foreach ($cartItems as $cartItem)
{
// @var Cart $cartItem
$product = $cartItem->product;
// Safety skip if product not found (should not happen in join)
if (!$product)
{
continue;
}
// Quantity available in product stock
$quantityProduct = $product->quantity;
if ($quantityProduct <= 0)
{
// Product out of stock - remove cart item
if (!$cartItem->delete())
{
ExceptionLogger::log(
new YiiDbException('Failed to delete cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
continue;
}
// If cart quantity more than available quantity - update cart quantity
if ($cartItem->quantity > $quantityProduct)
{
$cartItem->quantity = $quantityProduct;
$cartItem->total_price = MoneyHelper::totalAmount($quantityProduct, $product->price);
if (!$cartItem->save())
{
ExceptionLogger::log(
new YiiDbException('Failed to update cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
}
}
}
public function addItem(int $productId, int $quantity, bool $new = false): bool
{
$cart = $this->findCartItem($productId);
if ($cart === null)
{
// Item doesn't exist and we're not allowed to create a new one
if (!$new)
{
return false;
}
// Create new cart record
$cart = new Cart();
$cart->created_by = $this->_userId;
$cart->product_id = $productId;
$cart->quantity = 0;// start at zero, then increase
// Since this is a new item, treat quantity update as additive
$additive = true;
}
else
{
// For existing items, quantity update is not additive
$additive = false;
}
return $this->updateCartQuantity($cart, $quantity, $additive);
}
private function updateCartQuantity(Cart $cart, int $requestedQuantity, bool $additive): bool
{
$product = $cart->getProduct()->select(['quantity', 'price'])->asArray()->one();
if (!$product)
{
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
$inventory = (int) ArrayHelper::getValue($product, 'quantity', 0);
$price = (float) ArrayHelper::getValue($product, 'price', 0.0);
// Calculate new quantity
$currentQty = (int) $cart->quantity;
if ($additive)
{
$newQty = $currentQty + $requestedQuantity;
}
else
{
$newQty = $requestedQuantity;
}
// Enforce inventory limits — cap at available stock
if ($newQty > $inventory)
{
$newQty = $inventory;
}
// If quantity is zero or less, remove item instead of saving
if ($newQty <= 0)
{
return $cart->delete() !== false;
}
// If the quantity hasn't changed, no need to save; consider it successful
if ($newQty === $currentQty)
{
return true;
}
$cart->quantity = $newQty;
$cart->total_price = MoneyHelper::totalAmount($newQty, $price);
if (!$cart->save())
{
$errorMessage = 'Failed to save cart. Errors: ' . implode(', ', $cart->errors);
ExceptionLogger::log(new YiiDbException($errorMessage), 'cart_service_updateCartQuantity_error_', $cart);
return false;
}
return true;
}
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart)
{
return $cart->delete() !== false;
}
}
public function clearCart(): bool
{
return Cart::deleteAll(['created_by' => $this->_userId]) > 0;
}
public function getCartQuantity(): int
{
return (int) (Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity') ?? 0);
}
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item)
{
$price = $item->getProduct()->select('price')->scalar() ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
private function findCartItem(int $productId): ?Cart
{
return Cart::find()
->where(['created_by' => $this->userId, 'product_id' => $productId])
->one();
}
}
The goal is that both SessionCart and CartService are roughly the same, they handle to different tasks(session - guest, service - user)
but end goal is the same. thoughts?
CartService::getNavbarCartQuantity() is a nice helper for UI.
You might add similar for session cart.
B) Inventory Check and Efficiency:
CartService::checkInventory() eager loads products to avoid N+1 queries — good.
You are querying products one-by-one on SessionCart::checkInventory(), which could potentially be optimized by doing a single query for all product IDs in cart (maybe add Product::find()->where(['id' => $ids])->all()).
Both should update quantities/prices and remove out-of-stock items, you implement that.
Make sure both update the respective storage accordingly:
You're Product querying again in updateCartQuantity() inside addItem(), which could be optimized by caching the product fetched in checkInventory() or passed in parameters.
When calculating total price on getCartTotal(), you're doing
Optimization: eager load products in getCartItems() and use $item->product->price.
D) Error handling and logging is good in CartService with ExceptionLogger. Consider adding similar guards in SessionCart if any DB/session write errors happen.
E) Return types and nullability:
getCartQuantity() returns int, but SessionCart returns ?int.
Consider aligning to either return 0 or null if empty.
You might unify either way but be consistent.
F) In CartService::removeItem(), if item does not exist, no return statement (implicit null).
Consider adding explicit return false for clarity.
4) Example revision snippets to align CartService
Optimize getCartItems() to eager load products
php
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()
->with('product') // eager load product relation once
->where(['created_by' => $this->_userId])
->all();
}
Optimize getCartTotal()
php
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item)
{
// Use eager loaded related product without extra query
$price = $item->product->price ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
Fix removeItem() to return bool and explicit fallback
php
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart)
{
return $cart->delete() !== false;
}
return false;
}
Avoid repeated product lookups in updateCartQuantity()
Possibly pass the product object or data into the method or call checkInventory() first to have cached product info.
5) Further considerations
Transaction safety: When a user checkout or multiple changes happen, consider wrapping updates in DB transactions.
Concurrency: Inventory might still change between checkInventory and save; adapt to handle stock race conditions (e.g., pessimistic locking or retry).
Code reuse: For repeated logic like inventory validation, consider extracting common helpers or domain service class that both SessionCart and CartService can use, to keep logic DRY.
Interface: You might create a shared interface that both services implement (CartInterface), so your app can swap user guest/authorized cart implementation transparently.
6) Summary
Your CartService and SessionCart match the structure well and fulfill the respective needs of persistent and session cart management:
Both keep cart state consistent with current inventory,
Both add/update/remove items,
Both calculate totals and quantities.
With small improvements on caching, eager loading, and minor code cleanups suggested above, you can make them more efficient and aligned conceptually.
If you want, I can help create a unified interface or an abstract base class with common logic to reduce duplication between these two! Just say so. Otherwise, you’re on a great track.
Refactor updateCartQuantity() to accept a Product model if already fetched
In updateCartQuantity(), avoid querying product again if possible by passing the product info from checkInventory() or from addItem() when already known.
Here's an example:
php
private function updateCartQuantity(Cart $cart, int $requestedQuantity, bool $additive, ?Product $product = null): bool
{
if ($product === null) {
$product = $cart->product;
if ($product === null) {
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
$inventory = (int) $product->quantity;
$price = (float) $product->price;
$currentQty = (int) $cart->quantity;
$newQty = $additive ? $currentQty + $requestedQuantity : $requestedQuantity;
// Enforce inventory limits
if ($newQty > $inventory) {
$newQty = $inventory;
}
if ($newQty <= 0) {
return $cart->delete() !== false;
}
if ($newQty === $currentQty) {
return true;
}
$cart->quantity = $newQty;
$cart->total_price = MoneyHelper::totalAmount($newQty, $price);
if (!$cart->save()) {
$errorMessage = 'Failed to save cart. Errors: ' . implode(', ', $cart->errors);
ExceptionLogger::log(new YiiDbException($errorMessage), 'cart_service_updateCartQuantity_error_', $cart);
return false;
}
return true;
}
You’ll need to update calls accordingly. For example in addItem():
php
public function addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
{
$cart = $this->findCartItem($productId);
$product = Product::findOne($productId); // single query, reuse product model
if ($cart === null) {
if (!$createIfNotExists) {
return false;
}
$cart = new Cart();
$cart->created_by = $this->_userId;
$cart->product_id = $productId;
$cart->quantity = 0; // start zero
}
return $this->updateCartQuantity($cart, $quantity, $cart !== null, $product);
}
4) Return type consistency for getCartQuantity()
Options:
int with 0 meaning empty cart: simple, always defined, easier for consumers
?int with null meaning "no items": more explicit but requires null checks
Recommendation: For cart quantity, using int with 0 as empty is simpler & more practical in most scenarios (e.g. showing badge count: 0 means empty badges).
Change SessionCart accordingly:
php
public function getCartQuantity(): int
{
$items = $this->getCartItems();
if (empty($items)) {
return 0;
}
$sum = 0;
foreach ($items as $item) {
$sum += (int) ($item['quantity'] ?? 0);
}
return $sum;
}
5) Explicit return in removeItem()
Update:
php
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart) {
return $cart->delete() !== false;
}
return false;
}
Summary of changes:
Rename $new param to $createIfNotExists (or similar).
Add getNavbarCartQuantity() to SessionCart.
Eager load product relation in getCartItems().
Use eager loaded products in getCartTotal() to avoid N+1 queries.
Refactor updateCartQuantity() to accept existing Product object when available.
Standardize getCartQuantity() to always return int with 0 meaning empty.
Add explicit return false in removeItem() when no item found.
If you'd like, I can generate a complete updated CartService and SessionCart reflecting all these improvements. Just let me know!
namespace app\components;
use Yii;
use yii\db\Exception as YiiDbException;
use yii\helpers\ArrayHelper;
use app\models\Cart;
use app\models\Product;
use app\components\MoneyHelper;
use app\helpers\ExceptionLogger;
use app\helpers\LogHelper;
class CartService
{
private int $_userId;
public function __construct(int $userId)
{
$this->_userId = $userId;
}
/**
* Helper for displaying cart quantity in navbar/badge
*/
public function getNavbarCartQuantity(): ?int
{
$sum = Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity');
return $sum === null ? null : (int)$sum;
}
/**
* Returns cart items with eager loaded product relation
* Ensures inventory is checked & synced first.
*
* @return Cart[]
*/
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()
->with('product') // eager load products to avoid N+1 queries
->where(['created_by' => $this->_userId])
->all();
}
/**
* Validates cart items inventory and adjusts quantities accordingly.
* Removes cart items with no available stock.
*/
private function checkInventory(): void
{
$cartItems = Cart::find()
->alias('c')
->with('product') // eager load product relation
->where(['c.created_by' => $this->_userId])
->all();
foreach ($cartItems as $cartItem)
{
// @var Cart $cartItem
$product = $cartItem->product;
if (!$product) {
// Product missing - skip (should rarely happen)
continue;
}
$quantityProduct = (int) $product->quantity;
if ($quantityProduct <= 0) {
// Out of stock - remove cart item
if (!$cartItem->delete()) {
ExceptionLogger::log(
new YiiDbException('Failed to delete cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
continue;
}
if ($cartItem->quantity > $quantityProduct) {
$cartItem->quantity = $quantityProduct;
$cartItem->total_price = MoneyHelper::totalAmount($quantityProduct, $product->price);
if (!$cartItem->save()) {
ExceptionLogger::log(
new YiiDbException('Failed to update cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
}
}
}
/**
* Adds a product to the cart or updates existing quantity.
*
* @param int $productId Product ID
* @param int $quantity Quantity to add or set
* @param bool $createIfNotExists Whether to create a new cart item if none exists
* @return bool Success
*/
public function addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
{
$cart = $this->findCartItem($productId);
$product = Product::findOne($productId);
if ($cart === null) {
if (!$createIfNotExists) {
return false;
}
$cart = new Cart();
$cart->created_by = $this->_userId;
$cart->product_id = $productId;
$cart->quantity = 0; // start at zero; will add below
}
// If $cart was existing, additive = false (replace quantity)
// If new $cart, additive = true (increment from zero)
$additive = $cart->isNewRecord;
return $this->updateCartQuantity($cart, $quantity, $additive, $product);
}
/**
* Updates cart quantity enforcing inventory limits.
* Deletes cart item if quantity <= 0.
*
* @param Cart $cart Cart ActiveRecord
* @param int $requestedQuantity Quantity to add or set
* @param bool $additive Whether to add to current quantity or replace
* @param Product|null $product Optionally supply product to save query
* @return bool Success
*/
private function updateCartQuantity(Cart $cart, int $requestedQuantity, bool $additive, ?Product $product = null): bool
{
if ($product === null) {
$product = $cart->product;
if ($product === null) {
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
$inventory = (int) $product->quantity;
$price = (float) $product->price;
$currentQty = (int) $cart->quantity;
$newQty = $additive ? $currentQty + $requestedQuantity : $requestedQuantity;
// Enforce inventory limits — cap at available stock
if ($newQty > $inventory) {
$newQty = $inventory;
}
// Remove cart item if quantity zero or less
if ($newQty <= 0) {
return $cart->delete() !== false;
}
// If quantity unchanged, no need to save
if ($newQty === $currentQty) {
return true;
}
$cart->quantity = $newQty;
$cart->total_price = MoneyHelper::totalAmount($newQty, $price);
if (!$cart->save()) {
$errorMessage = 'Failed to save cart. Errors: ' . implode(', ', $cart->errors);
ExceptionLogger::log(new YiiDbException($errorMessage), 'cart_service_updateCartQuantity_error_', $cart);
return false;
}
return true;
}
/**
* Removes product from cart
*
* @param int $productId
* @return bool True if deleted, false otherwise or not found
*/
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart) {
return $cart->delete() !== false;
}
return false;
}
/**
* Clears entire cart for user
*
* @return bool True if any rows deleted, false otherwise
*/
public function clearCart(): bool
{
return Cart::deleteAll(['created_by' => $this->_userId]) > 0;
}
/**
* Total quantity in cart — 0 if empty
*
* @return int
*/
public function getCartQuantity(): int
{
return (int)(Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity') ?? 0);
}
/**
* Total price of all cart items
*
* @return float
*/
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item) {
$price = $item->product->price ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
/**
* Helper to find a Cart item for user's product
*
* @param int $productId
* @return Cart|null
*/
private function findCartItem(int $productId): ?Cart
{
return Cart::find()
->where(['created_by' => $this->_userId, 'product_id' => $productId])
->one();
}
}
If you need the matching SessionCart improvements, just ask!
false
Why is this check important?
It avoids redundant DB queries when the caller already passes the related Product.
It ensures the method always has the Product object to verify inventory and pricing before updating the cart.
It defends against inconsistent database states (or possible data corruption), where a cart might reference a missing product.
It provides graceful error handling and logging instead of crashing or throwing unhandled exceptions.
Summary
This snippet implements a fallback product fetching strategy, robustly handling missing or unavailable product data, and ensures that updateCartQuantity() has valid product info before proceeding with pricing and inventory enforcement. If it can’t get a product, it logs the issue and refuses to update the cart item, which is the safe and expected behavior.
public function __construct(int $userId)
{
$this->_userId = $userId;
}
/**
* Helper for displaying cart quantity in navbar/badge
*/
public function getNavbarCartQuantity(): ?int
{
$sum = Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity');
return $sum === null ? null : (int)$sum;
}
/**
* Returns cart items with eager loaded product relation
* Ensures inventory is checked & synced first.
*
* @return Cart[]
*/
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()
->with('product') // eager load products to avoid N+1 queries
->where(['created_by' => $this->_userId])
->all();
}
/**
* Validates cart items inventory and adjusts quantities accordingly.
* Removes cart items with no available stock.
*/
private function checkInventory(): void
{
$cartItems = Cart::find()
->alias('c')
->with('product') // eager load product relation
->where(['c.created_by' => $this->_userId])
->all();
foreach ($cartItems as $cartItem)
{
// @var Cart $cartItem
$product = $cartItem->product;
if (!$product) {
// Product missing - skip (should rarely happen)
continue;
}
$quantityProduct = (int) $product->quantity;
if ($quantityProduct <= 0) {
// Out of stock - remove cart item
if (!$cartItem->delete()) {
ExceptionLogger::log(
new YiiDbException('Failed to delete cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
continue;
}
if ($cartItem->quantity > $quantityProduct) {
$cartItem->quantity = $quantityProduct;
$cartItem->total_price = MoneyHelper::totalAmount($quantityProduct, $product->price);
if (!$cartItem->save()) {
ExceptionLogger::log(
new YiiDbException('Failed to update cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
}
}
}
/**
* Adds a product to the cart or updates existing quantity.
*
* @param int $productId Product ID
* @param int $quantity Quantity to add or set
* @param bool $createIfNotExists Whether to create a new cart item if none exists
* @return bool Success
*/
public function addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
{
$cart = $this->findCartItem($productId);
$product = Product::findOne($productId);
if ($cart === null) {
if (!$createIfNotExists) {
return false;
}
$cart = new Cart();
$cart->created_by = $this->_userId;
$cart->product_id = $productId;
$cart->quantity = 0; // start at zero; will add below
}
// If $cart was existing, additive = false (replace quantity)
// If new $cart, additive = true (increment from zero)
$additive = $cart->isNewRecord;
return $this->updateCartQuantity($cart, $quantity, $additive, $product);
}
/**
* Updates cart quantity enforcing inventory limits.
* Deletes cart item if quantity <= 0.
*
* @param Cart $cart Cart ActiveRecord
* @param int $requestedQuantity Quantity to add or set
* @param bool $additive Whether to add to current quantity or replace
* @param Product|null $product Optionally supply product to save query
* @return bool Success
*/
private function updateCartQuantity(Cart $cart, int $requestedQuantity, bool $additive, ?Product $product = null): bool
{
if ($product === null) {
$product = $cart->product;
if ($product === null) {
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
$inventory = (int) $product->quantity;
$price = (float) $product->price;
$currentQty = (int) $cart->quantity;
$newQty = $additive ? $currentQty + $requestedQuantity : $requestedQuantity;
// Enforce inventory limits — cap at available stock
if ($newQty > $inventory) {
$newQty = $inventory;
}
// Remove cart item if quantity zero or less
if ($newQty <= 0) {
return $cart->delete() !== false;
}
// If quantity unchanged, no need to save
if ($newQty === $currentQty) {
return true;
}
$cart->quantity = $newQty;
$cart->total_price = MoneyHelper::totalAmount($newQty, $price);
if (!$cart->save()) {
$errorMessage = 'Failed to save cart. Errors: ' . implode(', ', $cart->errors);
ExceptionLogger::log(new YiiDbException($errorMessage), 'cart_service_updateCartQuantity_error_', $cart);
return false;
}
return true;
}
/**
* Removes product from cart
*
* @param int $productId
* @return bool True if deleted, false otherwise or not found
*/
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart) {
return $cart->delete() !== false;
}
return false;
}
/**
* Clears entire cart for user
*
* @return bool True if any rows deleted, false otherwise
*/
public function clearCart(): bool
{
return Cart::deleteAll(['created_by' => $this->_userId]) > 0;
}
/**
* Total quantity in cart — 0 if empty
*
* @return int
*/
public function getCartQuantity(): int
{
return (int)(Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity') ?? 0);
}
/**
* Total price of all cart items
*
* @return float
*/
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item) {
$price = $item->product->price ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
/**
* Helper to find a Cart item for user's product
*
* @param int $productId
* @return Cart|null
*/
private function findCartItem(int $productId): ?Cart
{
return Cart::find()
->where(['created_by' => $this->_userId, 'product_id' => $productId])
->one();
}
}
refactor the code one more time, main areas checkInventory() and updateCartQuantity() and add a try and catch whenever saving data to a activeRecorder
namespace app\components;
use Yii;
use yii\db\Exception as YiiDbException;
use yii\helpers\ArrayHelper;
use app\models\Cart;
use app\models\Product;
use app\components\MoneyHelper;
use app\helpers\ExceptionLogger;
use app\helpers\LogHelper;
class CartService
{
private int $_userId;
public function __construct(int $userId)
{
$this->_userId = $userId;
}
/**
* Helper for displaying cart quantity in navbar/badge
*/
public function getNavbarCartQuantity(): ?int
{
$sum = Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity');
return $sum === null ? null : (int)$sum;
}
/**
* Returns cart items with eager loaded product relation.
* Ensures inventory is checked & synced first.
*
* @return Cart[]
*/
public function getCartItems(): array
{
$this->checkInventory();
return Cart::find()
->with('product') // eager load products to avoid N+1 queries
->where(['created_by' => $this->_userId])
->all();
}
/**
* Validates cart item inventories and adjusts quantities accordingly.
* Removes cart items if out of stock or quantities adjusted.
*/
private function checkInventory(): void
{
$cartItems = Cart::find()
->alias('c')
->with('product') // eager load product relation
->where(['c.created_by' => $this->_userId])
->all();
foreach ($cartItems as $cartItem) {
/** @var Cart $cartItem */
$product = $cartItem->product;
// Skip if product is missing, should rarely happen
if (!$product) {
continue;
}
$availableQty = (int)$product->quantity;
if ($availableQty <= 0) {
// Product out of stock, remove cart item
try {
if (!$cartItem->delete()) {
ExceptionLogger::log(
new YiiDbException('Failed to delete out-of-stock cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_checkInventory_exception_', $cartItem);
}
continue;
}
// If cart quantity exceeds available stock, update it
if ($cartItem->quantity > $availableQty) {
$cartItem->quantity = $availableQty;
$cartItem->total_price = MoneyHelper::totalAmount($availableQty, $product->price);
try {
if (!$cartItem->save()) {
ExceptionLogger::log(
new YiiDbException('Failed to update cart item quantity during inventory check.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_checkInventory_exception_', $cartItem);
}
}
}
}
/**
* Adds or updates product quantity in cart.
*
* @param int $productId
* @param int $quantity
* @param bool $createIfNotExists Whether to create new cart item if none exists
* @return bool
*/
public function addItem(int $productId, int $quantity, bool $createIfNotExists = false): bool
{
$cart = $this->findCartItem($productId);
$product = Product::findOne($productId);
if ($cart === null) {
if (!$createIfNotExists) {
return false;
}
$cart = new Cart();
$cart->created_by = $this->_userId;
$cart->product_id = $productId;
$cart->quantity = 0; // start at zero so additive=true below
}
// If new cart record, additive = true (increment)
// If existing cart record, additive = false (replace)
$additive = $cart->isNewRecord;
return $this->updateCartQuantity($cart, $quantity, $additive, $product);
}
/**
* Updates cart quantity ensuring it respects stock availability.
* Deletes cart item if new quantity <= 0.
*
* @param Cart $cart
* @param int $requestedQuantity
* @param bool $additive
* @param Product|null $product
* @return bool
*/
private function updateCartQuantity(Cart $cart, int $requestedQuantity, bool $additive, ?Product $product = null): bool
{
if ($product === null) {
$product = $cart->product;
if ($product === null) {
LogHelper::error("Product not found for cart update: ID {$cart->product_id}", [
'product ID' => $cart->product_id,
'method' => __METHOD__
]);
return false;
}
}
$inventory = (int)$product->quantity;
$price = (float)$product->price;
$currentQty = (int)$cart->quantity;
$newQty = $additive ? $currentQty + $requestedQuantity : $requestedQuantity;
// Clamp quantity to available stock
if ($newQty > $inventory) {
$newQty = $inventory;
}
// Delete cart item if quantity zero or less
if ($newQty <= 0) {
try {
return $cart->delete() !== false;
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_updateCartQuantity_delete_exception_', $cart);
return false;
}
}
// If quantity unchanged, no need to save
if ($newQty === $currentQty) {
return true;
}
$cart->quantity = $newQty;
$cart->total_price = MoneyHelper::totalAmount($newQty, $price);
try {
if (!$cart->save()) {
$errorMessage = 'Failed to save cart. Errors: ' . implode(', ', $cart->errors);
ExceptionLogger::log(new YiiDbException($errorMessage), 'cart_service_updateCartQuantity_error_', $cart);
return false;
}
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_updateCartQuantity_exception_', $cart);
return false;
}
return true;
}
/**
* Removes the product from cart
*
* @param int $productId
* @return bool True if removed or deleted successfully, false otherwise
*/
public function removeItem(int $productId): bool
{
$cart = Cart::find()->where([
'created_by' => $this->_userId,
'product_id' => $productId
])->one();
if ($cart) {
try {
return $cart->delete() !== false;
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_removeItem_exception_', $cart);
return false;
}
}
return false;
}
/**
* Clears the entire cart for the user
*
* @return bool True if any rows deleted, false otherwise
*/
public function clearCart(): bool
{
try {
return Cart::deleteAll(['created_by' => $this->_userId]) > 0;
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'cart_service_clearCart_exception_');
return false;
}
}
/**
* Returns total quantity in user's cart (0 if empty)
*
* @return int
*/
public function getCartQuantity(): int
{
return (int)(Cart::find()->where([
'created_by' => $this->_userId
])->sum('quantity') ?? 0);
}
/**
* Returns total price of all items in cart
*
* @return float
*/
public function getCartTotal(): float
{
$items = $this->getCartItems();
$sum = 0.0;
foreach ($items as $item) {
$price = $item->product->price ?? 0;
$sum += $item->quantity * $price;
}
return $sum;
}
/**
* Finds the Cart item by productId for this user
*
* @param int $productId
* @return Cart|null
*/
private function findCartItem(int $productId): ?Cart
{
return Cart::find()
->where(['created_by' => $this->_userId, 'product_id' => $productId])
->one();
}
}
What was changed:
Wrapped all save() and delete() calls inside try-catch blocks to catch and log exceptions (including unexpected ones).
ExceptionLogger::log() is called in catch blocks to record any failures.
Inside checkInventory() added try-catch around both deletes and saves.
Inside updateCartQuantity() added try-catch for deletes and saves.
removeItem() and clearCart() also catch exceptions.
Code logic otherwise remains unchanged; improves robustness to DB exceptions.
Feel free to ask if you'd like me to also refactor SessionCart with similar error handling or discuss further improvements!
Or example #2 — Log without throwing:
php
if ($quantityProduct <= 0)
{
// Product out of stock - remove cart item
try
{
if (!$cartItem->delete())
{
ExceptionLogger::log(
new YiiDbException('Failed to delete cart item.'),
'cart_service_checkInventory_error_',
$cartItem
);
}
continue;
}
catch (Throwable $e)
{
ExceptionLogger::log(
$e,
'cart_service_checkInventory_exception_',
$cartItem
);
}
}
Summary
Just creating an exception (new ...) without throw or logging doesn't report errors.
If you want to catch failed delete and log it, either throw and catch or log directly without throwing.
Both approaches are valid; pick what fits your code style and error handling policy.
If you want me to update the whole method consistently, just ask!
class CartController extends BaseController
{
private CartService $_cartUser;
public function init()
{
/**
* Call to parent constructor
*
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
// ... initialization after configuration is applied...
/**
* Cart Service (for user)
* @see app\components\CartService.php
*/
$this->_cartUser = new CartService($this->_userId);
}
/**
* Behaviors
* @return array
*/
public function behaviors(): array
{
$behaviors = [];
/**
* Access Control
* @url https://www.yiiframework.com/doc/guide/2.0/en/structure-filters#access-control
*/
$behaviors['access'] = [
'class' => AccessControl::class,
'rules' => [
[
// User and Guest can do the following:
'actions' => [
'index',
'add',
'delete',
'clear',
'purchase',
'buy-now',
'cancel',
'success'
],
'allow' => true,
'roles' => ['@', '?'],
],
],
];
/**
* Verb Filter
* @url https://www.yiiframework.com/doc/guide/2.0/en/structure-filters#verb-filter
*/
$behaviors['verbs'] = [
'class' => VerbFilter::class,
'actions' => [
'index' => ['get', 'post'],
'add' => ['post'],
'delete' => ['post'],
'clear' => ['post'],
'purchase' => ['post'],
'buy-now' => ['post'],
'cancel' => ['get'],
'success' => ['get'],
],
];
if ($this->_rlEnable) {
/**
* Rate Limiter
* @see filters\IpRateLimiter.php
* @see filters\IpRateLimitInterface.php
*/
$behaviors['ratelimiter'] = [
'class' => IpRateLimiter::class,
'rateLimit' => $this->_rlMaxRequest ?? 100,
'timePeriod' => $this->_rlTimePeriod ?? 3600,
'separateRates' => $this->_rlSeparateRates ?? true,
'enableRateLimitHeaders' => $this->_rlRateHeaders ?? true,
];
}
return $behaviors;
}
/**
* Actions
* @url https://www.yiiframework.com/doc/api/2.0/yii-base-controller#$action-detail
* @return array
*
public function actions(): array {}//*/
public function actionIndex(): string
{
$pageTitle = \Yii::t('app', 'cart');
// Set Meta Data for website title, keywords and description.
$this->setMeta($pageTitle, 'cart, shopping cart', null);
// Set page breadcrumbs. (optional)
\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now.
// Setup model
$model = new CartUpdateForm();
// This is: $request->isGet
if (this->_isGuest)
{
// Guest: get cart data from session cart
$cartItems = $this->_sessionCart->getCartItems();
$model->items = [];
foreach ($cartItems as $productId => $itemData)
{
$model->items[] = [
'productId' => (int) $productId,
'quantity' => (int) $itemData['quantity']
];
}
}
else
{
// User: get cart data from cart service
$cartItems = $cartService->getCartItems();
$model->items = [];
foreach ($cartItems as $item)
{
$model->items[] = [
'productId' => (int) $item->product_id,
'quantity' => (int) $item->quantity,
];
}
}
$request = \Yii::$app->request;
if (($request->isPost) && ($model->load($request->post()) && $model->validate()))
{
if (this->_isGuest)
{
foreach ($model->items as $item)
{
$pid = $item['productId'];
$qty = $item['quantity'];
if ($qty > 0)
{
$this->_sessionCart->addItem($pid, $qty);
}
else
{
$this->_sessionCart->removeItem($pid);
}
}
}
else
{
foreach ($model->items as $item)
{
$pid = $item['productId'];
$qty = $item['quantity'];
if ($qty > 0)
{
$this->_cartService->addItem($pid, $qty);
}
else
{
$this->_cartService->removeItem($pid);
}
}
}
}
\Yii::$app->session->setFlash('success', 'Cart updated successfully.');
return $this->render('index', [
'model' => $model
]);
//return $this->refresh();
}
/**
* Add To Cart
* @see app\models\forms\CartAddForm.php
*/
public function actionAdd()
{
$model = new CartAddForm();
$request = \Yii::$app->request;
if (($request->isPost) && ($model->load($request->post()) && $model->validate()))
{
$product = Product::findOne($form->productId);
if (!$product)
{
throw new YiiWebNotFoundHttpException(\Yii::t('app', 'Product not found.'));
}
if ($this->_isGuest)
{
$added = $this->_sessionCart->addItem($form->productId, $form->quantity);
}
else
{
$added = $this->_cartService->addItem($form->productId, $form->quantity, true);
}
if ($added)
{
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Product added to cart.'));
}
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Could not add product to cart.'));
}
$products = Product::find()->select(['name', 'id'])->indexBy('id')->column();
return $this->render('add', [
'model' => $form,
'products' => $products,
]);
}
}
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\components\CartService;
use app\models\Product;
use app\models\forms\CartAddForm;
use app\models\forms\CartUpdateForm;
class CartController extends BaseController
{
private CartService $_cartService;
private SessionCart $_sessionCart;
public function init()
{
parent::init();
// Initialize CartService for logged-in user
$this->_cartService = new CartService($this->_userId);
// Initialize SessionCart for guests (Assuming $this->_sessionUser injected/set in BaseController)
$this->_sessionCart = new SessionCart($this->_sessionUser);
}
public function behaviors(): array
{
$behaviors = [];
$behaviors['access'] = [
'class' => AccessControl::class,
'rules' => [
[
'actions' => [
'index', 'add', 'delete', 'clear',
'purchase', 'buy-now', 'cancel', 'success'
],
'allow' => true,
'roles' => ['@', '?'], // both guests and users allowed
],
],
];
$behaviors['verbs'] = [
'class' => VerbFilter::class,
'actions' => [
'index' => ['get', 'post'],
'add' => ['post'],
'delete' => ['post'],
'clear' => ['post'],
'purchase' => ['post'],
'buy-now' => ['post'],
'cancel' => ['get'],
'success' => ['get'],
],
];
// Add rate limiter if enabled (assuming _rlXXX properties set in BaseController)
if ($this->_rlEnable) {
$behaviors['ratelimiter'] = [
'class' => IpRateLimiter::class,
'rateLimit' => $this->_rlMaxRequest ?? 100,
'timePeriod' => $this->_rlTimePeriod ?? 3600,
'separateRates' => $this->_rlSeparateRates ?? true,
'enableRateLimitHeaders' => $this->_rlRateHeaders ?? true,
];
}
return $behaviors;
}
/**
* Show the cart index page with optionally updating quantities.
*/
public function actionIndex(): string
{
$pageTitle = \Yii::t('app', 'Cart');
$this->setMeta($pageTitle, 'cart, shopping cart', null);
\Yii::$app->layoutManager->addBreadcrumb($pageTitle);
$model = new CartUpdateForm();
// Load existing cart items into the form model
if ($this->_isGuest) {
// Guest cart from session
$cartItems = $this->_sessionCart->getCartItems();
$model->items = [];
foreach ($cartItems as $productId => $itemData) {
$model->items[] = [
'productId' => (int)$productId,
'quantity' => (int)($itemData['quantity'] ?? 0),
];
}
} else {
// Authenticated user cart
$cartItems = $this->_cartService->getCartItems();
$model->items = [];
foreach ($cartItems as $item) {
$model->items[] = [
'productId' => (int)$item->product_id,
'quantity' => (int)$item->quantity,
];
}
}
$request = \Yii::$app->request;
if ($request->isPost && $model->load($request->post()) && $model->validate()) {
// Process update / quantity changes
if ($this->_isGuest) {
foreach ($model->items as $item) {
$pid = $item['productId'];
$qty = $item['quantity'];
if ($qty > 0) {
$this->_sessionCart->addItem($pid, $qty);
} else {
$this->_sessionCart->removeItem($pid);
}
}
} else {
foreach ($model->items as $item) {
$pid = $item['productId'];
$qty = $item['quantity'];
if ($qty > 0) {
$this->_cartService->addItem($pid, $qty, true);
} else {
$this->_cartService->removeItem($pid);
}
}
}
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Cart updated successfully.'));
return $this->refresh();
}
return $this->render('index', [
'model' => $model,
]);
}
/**
* Add product to cart action.
*/
public function actionAdd()
{
$form = new CartAddForm();
$request = \Yii::$app->request;
if ($request->isPost && $form->load($request->post()) && $form->validate()) {
$product = Product::findOne($form->productId);
if (!$product) {
throw new NotFoundHttpException(\Yii::t('app', 'Product not found.'));
}
if ($this->_isGuest) {
$added = $this->_sessionCart->addItem($form->productId, $form->quantity);
} else {
$added = $this->_cartService->addItem($form->productId, $form->quantity, true);
}
if ($added) {
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Product added to cart.'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Could not add product to cart.'));
}
// Redirect back or to cart page
return $this->redirect(['cart/index']);
}
// Simple product list for selection (you can improve loading with actual product data)
$products = Product::find()->select(['name', 'id'])->indexBy('id')->column();
return $this->render('add', [
'model' => $form,
'products' => $products,
]);
}
// TODO: Implement other controller actions: delete, clear, purchase, buy-now, cancel, success
}
Key fixes and improvements
Added missing use statements, e.g. NotFoundHttpException.
Consistently use $this->_cartService (not $cartService) in actionIndex.
Added initialization for the $this->_sessionCart instance in init().
Fixed $form vs $model naming in actionAdd.
Ensure actionIndex handles POST correctly and refreshes after successful update.
Added redirects after adding item in actionAdd.
Added comments and structure for further action methods.
For $this->_isGuest, it’s assumed you have such a property/method or you can check Yii::$app->user->isGuest.
You may want to adjust or add error handling/flash messages as needed.
Implement UI views (index, add, etc.) based on the forms and models.
If you want me to help implement any of the missing actions or fully polish this controller, just let me know!
public function actionPurchase(): \yii\web\Response
{
if ($this->_isGuest) {
// Redirect guest to login, or handle guest checkout
\Yii::$app->session->setFlash('info', \Yii::t('app', 'Please log in to complete purchase.'));
return $this->redirect(['site/login']);
}
// Here you’d typically collect payment info, shipping, etc.
// For demo, assume a simple order creation
$cartItems = $this->_cartService->getCartItems();
if (empty($cartItems)) {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Your cart is empty.'));
return $this->redirect(['cart/index']);
}
// TODO: Implement Order creation logic here
// For example:
// $order = new Order([...]);
// save order and order items
\Yii::$app->session->setFlash('success', \Yii::t('app', 'Your order has been placed!'));
// Clear cart after successful order
$this->_cartService->clearCart();
return $this->redirect(['cart/success']);
}
4. actionBuyNow — Add single item and immediately checkout
php
public function actionBuyNow(): \yii\web\Response
{
$request = \Yii::$app->request;
$productId = $request->post('productId');
$quantity = (int)$request->post('quantity', 1);
if (!$productId || $quantity <= 0) {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Invalid product or quantity.'));
return $this->redirect(['cart/index']);
}
$added = $this->_isGuest
? $this->_sessionCart->addItem((int)$productId, $quantity)
: $this->_cartService->addItem((int)$productId, $quantity, true);
if ($added) {
// Redirect to purchase or checkout page
return $this->redirect(['cart/purchase']);
} else {
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Failed to add product to cart.'));
return $this->redirect(['product/view', 'id' => $productId]);
}
}
5. actionCancel — Cancel order process (usually a GET redirect)
php
public function actionCancel(): \yii\web\Response
{
\Yii::$app->session->setFlash('info', \Yii::t('app', 'Checkout canceled.'));
return $this->redirect(['cart/index']);
}
6. actionSuccess — Thank you / success page
php
public function actionSuccess(): string
{
$this->setMeta(\Yii::t('app', 'Order Success'), null, null);
\Yii::$app->layoutManager->addBreadcrumb(\Yii::t('app', 'Order Success'));
return $this->render('success');
}
Notes
Adjust flash messages and redirections as per your app flow.
You might want to implement full Order/Payment integration in purchase and buy-now.
The controller assumes presence of $_isGuest, $_sessionCart, and $_cartService properties as earlier.
Protect against invalid requests; add more validation/security as needed.
Returns mostly redirects for POST actions (PRG pattern).
Would you like me to help build any related forms, models, or views next?
$items
2. Models
You already have:
Product – your product AR model.
Cart – persistent cart items AR.
No new AR models are required for the basic cart.
If you implement order processing, you may add:
Order / OrderItem models
Payment model
3. Views
a) Cart Index View (views/cart/index.php)
Render cart items, total, and provide update form.
<?php
$this->title = Yii::t('app', 'Order Success');
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>
<p><?= Yii::t('app', 'Thank you for your purchase! Your order has been placed.') ?></p>
<?= \yii\helpers\Html::a(Yii::t('app', 'Continue Shopping'), ['/site/index'], ['class' => 'btn btn-primary']) ?>
Summary
Forms provide validation and data handling before controller passes to services.
Views render forms and user interaction for updating and adding cart items.
Models are mainly your existing entities (Cart, Product), plus future Order if implementing checkout.
If you want, I can generate fully working form models with validation scenarios or build more polished views including product info display and AJAX features—just ask!
2. Polished Cart Index View with Product Info & AJAX Quantity Update
This example uses jQuery for AJAX calls when user changes quantities, improving UX by avoiding full page reloads.
Shows product title, price, quantity input (min=0 to remove), line total, and remove button.
JS updates totals live on quantity change or item removal.
You can enable AJAX submit (commented out block) for better UX.
Prices are formatted as currency.
Assumes you pass from controller an array $products indexed by product ID for quick lookup.
3. Controller changes to support the improved view with products data
Modify actionIndex():
php
public function actionIndex(): string
{
// ... existing code to build $model of CartUpdateForm with items ...
// Fetch all product models for the products currently in cart to pass to view
$productIds = array_column($model->items, 'productId');
$products = Product::find()->where(['id' => $productIds])->indexBy('id')->all();
return $this->render('index', [
'model' => $model,
'products' => $products,
]);
}
Next steps
Implement similar AJAX + nice UI for Add to Cart form.
Build views for purchase, success pages with payment integration placeholders.
Add unit & functional tests for forms and controllers.
If you'd like I can prepare the AJAX-enabled Add to Cart form/view next or help you scaffold the Order/Checkout flow — just say!