Thanks for the detailed explanation of your issue.
The core problem:
Your current CartController and _sessionCart component seem designed with a single abstraction for cart management, but in reality:
- Guests' cart data lives in the session only.
- Logged-in users have their cart data stored in a database-backed Cart ActiveRecord model.
Consequently, _sessionCart struggles to perform database operations or reflect DB cart changes because it only manages session storage.
How to resolve this cleanly?
Approach:
- Create a CartService or CartManager class to abstract cart operations for both guests and logged-in users.
This Service would:
- Detect if the user is a guest.
- Delegate to a session-based cart for guests.
- Delegate to a DB-backed cart model for logged-in users.
- Provide a unified API for
add, remove, update, clear, getItems, persist etc.
- Refactor your controller to talk only with this CartService.
Example Large Conceptual Outline:
class CartService
{
/** @var SessionManager */
protected $sessionManager;
/** @var int|null */
protected $userId;
/** @var SessionCart */
protected $sessionCart;
/** @var CartAR|null */
protected $cartModel;
public function __construct($userId = null, SessionManager $sessionManager)
{
$this->userId = $userId;
$this->sessionManager = $sessionManager;
$this->sessionCart = new SessionCart(new SessionUser($sessionManager));
if ($userId !== null) {
// load or create DB cart model for user
$this->cartModel = CartAR::findOne(['user_id' => $userId]) ?? new CartAR(['user_id' => $userId]);
}
}
public function getItems(): array
{
if ($this->userId === null) {
return $this->sessionCart->getCartSession();
} else {
return $this->cartModel->getCartItems(); // Assume returns [productId => quantity]
}
}
public function addProduct(int $productId, int $qty)
{
if ($this->userId === null) {
return $this->sessionCart->addToCartProduct($productId, $qty);
} else {
$this->cartModel->addProduct($productId, $qty);
return $this->cartModel->save();
}
}
public function updateProduct(int $productId, int $qty)
{
if ($this->userId === null) {
if ($qty > 0) {
$this->sessionCart->addToCartProduct($productId, $qty);
} else {
$this->sessionCart->removeFromCart($productId);
}
} else {
if ($qty > 0) {
$this->cartModel->updateProductQuantity($productId, $qty);
} else {
$this->cartModel->removeProduct($productId);
}
$this->cartModel->save();
}
}
public function clear()
{
if ($this->userId === null) {
$this->sessionCart->clearCart();
} else {
$this->cartModel->clearCart();
$this->cartModel->save();
}
}
public function persist()
{
// If guest logs in, move session cart to DB cart
if ($this->userId !== null) {
$sessionItems = $this->sessionCart->getCartSession();
foreach ($sessionItems as $productId => $itemData) {
$this->cartModel->addProduct($productId, $itemData['quantity']);
}
if ($this->cartModel->save()) {
$this->sessionCart->clearCart();
}
}
}
}
Updating your controller (an example for actionAdd and actionIndex):
public function init()
{
parent::init();
$sessionManager = new SessionManager();
$userId = Yii::$app->user->isGuest ? null : Yii::$app->user->id;
$this->cartService = new CartService($userId, $sessionManager);
}
public function actionAdd()
{
$form = new AddToCartForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
$product = Product::findOne($form->productId);
if (!$product) {
throw new NotFoundHttpException('Product not found');
}
$added = $this->cartService->addProduct($form->productId, $form->quantity);
if ($added) {
if (!Yii::$app->user->isGuest) {
$this->cartService->persist();
}
Yii::$app->session->setFlash('success', 'Product added to cart.');
return $this->redirect(['cart/index']);
}
Yii::$app->session->setFlash('error', 'Could not add product to cart.');
}
$products = Product::find()->select(['name', 'id'])->indexBy('id')->column();
return $this->render('add', [
'model' => $form,
'products' => $products,
]);
}
public function actionIndex()
{
$form = new CartUpdateForm();
$cartItems = $this->cartService->getItems() ?? [];
$form->items = [];
foreach ($cartItems as $productId => $itemData) {
$form->items[] = [
'productId' => (int)$productId,
'quantity' => (int)$itemData['quantity'],
];
}
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
foreach ($form->items as $item) {
$this->cartService->updateProduct($item['productId'], $item['quantity']);
}
if (!Yii::$app->user->isGuest) {
$this->cartService->persist();
}
Yii::$app->session->setFlash('success', 'Cart updated successfully.');
return $this->refresh();
}
$productIds = array_column($form->items, 'productId');
$products = Product::find()->where(['id' => $productIds])->indexBy('id')->all();
return $this->render('index', [
'form' => $form,
'products' => $products,
]);
}
Summary:
- You must separate session cart and DB cart concerns because they persist data differently.
- A CartService/Manager abstraction can cleanly provide a consistent API to the rest of your app.
- Cart synchronization between session and DB is done in
persist() when user logs in or cart updates.
- The controller becomes simpler and only calls
cartService methods.
- Your existing
SessionCart and DB Cart ActiveRecord remain, but wrapped to avoid duplication and confusing responsibility.
If you want, I can help you write any of the specific model methods or flesh out the CartService/ActiveRecord behaviors! Would you like me to?