Magento Product Collection

Many a time I have seen code where coders are doing all the product manipulation and work within PHP and not letting Magento do the work. Now, there is a caveat here that depending on the data you’re using, this could actually be quicker, but I think for the majority of cases, this is just lack of understanding.

So, I thought I’d knock up a quick post with some pointers on using the Magento Product Collection to simplify and speed up the data you’re getting.

The Product Collection class in Magento is a Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection. It should, in theory always return an array of product objects. The product objects it returns however are not the full product object you might be expecting, but it depends how you want to manipulate the data that comes back. Lets take a look at some of the functions we can use against it to get data.

Getting all products

PHP

1

2

$collection=Mage::getResourceModel('catalog/product_collection')

->setStoreId($this->getStoreId());

So, how can we loop through this?

PHP

1

2

3

4

5

foreach($collectionas$product){

// you may want to load the full product object - you can do this from the ID