Difference between two commands of fetching Shopping Cart Items in Magento

醉酒当歌 提交于 2019-12-23 19:43:18

问题


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:


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


来源:https://stackoverflow.com/questions/3042905/difference-between-two-commands-of-fetching-shopping-cart-items-in-magento

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!