简体   繁体   中英

Difference between two commands of fetching Shopping Cart Items in Magento

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM