Magento – Getting New Session Id before session expires,checkout/session car is empty even cart has item

addtocartmagento-1.7sessionsingleton

I have a local module, which adds product to cart.To add to cart i have some conditional check before adding to cart,and i am using getSingleton('checkout/session')->getQuote() object for getting number of items in cart.

My code, initially checks number of items in cart in that session,by below code.

if(Mage::getSingleton('checkout/session')->getQuote()->hasItems())
{
}

adding Product to cart code,

$cart = Mage::getModel('checkout/cart');
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
$cart->addProduct($product, $params);
$cart->save();
$this->_getSession()->setCartWasUpdated(true);

My Question is , sometimes hasItems() returns false even my cart has products.

EDIT

I tried logging session_id(), an i found that this session_id changed unexpectedly. That means new session is created , so my cart is empty in this new session.

My Question?

I dont create any session in my code, then why new session is created before the session timeout?

Best Answer

You are calling checkout/session model in wrong way. It should be

 Mage::getSingleton('checkout/session');

So your condition will look like

if (Mage::getSingleton('checkout/session')->getQuote()->hasItems()) {
    //do your stuff here
}
Related Topic