views:

234

answers:

2

In Magento, if you need to get / fetch the Shopping Cart's Item details, you can do it in any of the two possible ways, which will provide you with all the shopped Items in an array:-

  1. $cartItems1 = $cart->getQuote()->getAllItems();
  2. $cartItems2 = $cart->getItems()->getData();

But before using any one of the above two methods, you need to initialize the shopping cart object as:-

$cart = new Mage_Checkout_Model_Cart();
$cart->init();

Can anyone please describe in details as to what the two options provide & their differences between each other, along with their possible usage.

In any more such option is available in Magento, can anyone please highlight it?

+1  A: 

If you look at the code of the Cart and Quote classes everything will become clear.

Here's the code for $cart->getItems():

public function getItems()
{
  return $this->getQuote()->getAllVisibleItems();
}

Plain and simple - it just calls a method of the Quote object. So the question now is: What is the difference between getAllVisibleItems() and getAllItems()?

Let's look at the code of both methods:

public function getAllItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
        if (!$item->isDeleted()) {
            $items[] =  $item;
        }
    }
    return $items;
}

public function getAllVisibleItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
        if (!$item->isDeleted() && !$item->getParentItemId()) {
            $items[] =  $item;
        }
    }
    return $items;
}

The only difference: getAllVisibleItems() has an additional check for each item:

!$item->getParentItemId()

which tests if the product has a parent (in other words, it tests if it is a simple product). So this method's return array will be missing simple products, as opposed to getAllItems().

Are there any other ways to retrieve items?

One would be to directly get the product collection from the quote object:

$productCollection = $cart->getQuote()->getItemsCollection();
silvo
@Silvo - Wow, really thanks for such a beautiful answer. Many thanks.
Knowledge Craving
You are welcome. If you find this answer helpful, please accept it.
silvo
@silvo - I was actually waiting for such more good answers, if any were posted. But nevertheless, I have accepted your answer.
Knowledge Craving
A: 

can you plese tell me how can I fetch shipping cost and time from cart object?

@user450353 - Please don't post any new unrelated questions in another question post's answer area. By default, SO provides the basic advantage to any new user to post any programmatic question, without any need of reputation points. I hope, you have understood my point.
Knowledge Craving