0

I read these 3 snippets from the Internet of obtaining shopping cart contents.

Snippet 1

$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
    // get item details here
}

Snippet 2

$cartItems = Mage::getModel("checkout/cart")->getItems();
foreach($cartItems as $item) {
    // get item details here
}

Snippet 3

$cartHelper = Mage::helper('checkout/cart');
$cartItems = $cartHelper->getCart()->getItems();
foreach($cartItems as $item) {
    // get item details here
}

What are the difference the snippets above? All of them return the same items.

  • What are you trying to achieve? – SR_Magento Jan 19 '15 at 12:39
2

1.

$cartItems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();

Will return all visible items in the cart. For more info on visible / not visible items look here. (In short, this kind of function would return a configurable but not its simple)

2.

$cartItems = Mage::getModel("checkout/cart")->getItems();

Mage_Checkout_Model_Cart
public function getItems()
{
    if (!$this->getQuote()->getId()) {
        return array();
    }
    return $this->getQuote()->getItemsCollection();
}

Under the hood it is getting the quote and getting the items collection, so will not be doing visible filtering as scenario 1. (In short, this kind of function would return a configurable AS WELL AS its simple)

3.

$cartItems = Mage::helper('checkout/cart')->getCart()->getItems()

Mage_Checkout_Helper_Cart
/**
 * Retrieve cart instance
 *
 * @return Mage_Checkout_Model_Cart
 */
public function getCart()
{
    return Mage::getSingleton('checkout/cart');
}

Under the hood this calls getSingleton('checkout/cart'), from there it's the same as scenario 2.

So the main difference is in 1, where it filters for visible items.

0

Snippet 1

$quote = Mage::getSingleton('checkout/session')->getQuote(); give Current cart Object.It provide.

Snippet 2

$cartItems = Mage::getModel("checkout/cart")->getItems();

Snippet 3

$cartHelper = Mage::helper('checkout/cart');
$cartItems = $cartHelper->getCart();

Here:

Mage::getSingleton('checkout/cart')=$cartHelper->getCart()

Mage::getSingleton('checkout/cart') give singleton object of Class Mage_Checkout_Model_Cart.

and $cartItems->getItems() give null value if current session did not have any cart items. please check on this class

public function getItems()
    {
    //  !$this->getQuote() =Mage::getSingleton('checkout/session')->getQuote()
        if (!$this->getQuote()->getId()) { 
            return array();
        }
        return $this->getQuote()->getItemsCollection();
    }

** More details will provide soon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.