Creating a Reusable Product Collection Block in Magento
As you’re working on your Magento project, you’ll often find yourself needing to display specific collections of productsâlike best-selling items or most viewed productsâin various parts of your store. While it’s convenient to call the collection directly in your template files, this approach can lead to repetitive code and makes it harder to maintain your site over time.
The better solution is to create a reusable block that encapsulates the collection logic. This allows you to keep your templates clean, promotes reuse across different parts of your store, and simplifies updates if you need to modify your collection criteria. In this post, we’ll walk through how to create such a block for displaying best-selling products.
Creating the Block
First, let’s assume you have already set up your custom module in Magento. If not, check out our guide on how to create a new module for a step-by-step walkthrough.
Within this module, navigate to app/code/local/YourVendor/YourModule/Block. Here, create a new file called Bestselling.php (or any name that reflects the purpose of your collection).
In this block, you’ll define your function for creating the best-selling product collection:
<?php
class YourVendor_YourModule_Block_Bestselling extends Mage_Core_Block_Template
{
protected function _getBestsellingCollection()
{
$visibility = array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_bestsellingCollection = Mage::getResourceModel('reports/product_collection');
$_bestsellingCollection->addAttributeToSelect('name')
->addAttributeToFilter('visibility', $visibility)
->addOrderedQty()
->setOrder('ordered_qty', 'desc');
$_bestsellingCollection->load();
return $_bestsellingCollection;
}
public function getLoadedBestsellingCollection()
{
return $this->_getBestsellingCollection();
}
}
This code defines a _getBestsellingCollection method that creates and loads the product collection based on your desired criteria. The getLoadedBestsellingCollection method simply calls this internal method, providing a public interface for using the block in other parts of your code.
Using the Block in Your Template
Now that you have the block created, you can use it directly within any template file:
<?php
$_productCollection = $this->getLoadedBestsellingCollection();
?>
This code retrieves the best-selling product collection from your new block and stores it in $_productCollection. You can then loop through this collection to display the products:
<ul>
<?php foreach ($_productCollection as $_product): ?>
<li><a href="<?php echo $this->getProductUrl($_product) ?>"><?php echo $_product->getName() ?></a></li>
<?php endforeach; ?>
</ul>
Encapsulating the Collection Logic
You mentioned in your update that you’re trying to extend the Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection class to encapsulate your collection logic. This approach can work, but it requires a deeper understanding of Magento’s object model and requires more setup.
To achieve this, create a new file called Bestseller.php in app/code/local/YourVendor/YourModule/Model:
<?php
class YourVendor_YourModule_Model_Bestseller extends Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
{
public function addBestSelling()
{
$this->addAttributeToSelect('*')->addOrderedQty()->setOrder('ordered_qty', 'desc');
return $this;
}
}
Next, you need to make Magento aware of this new model. In your module’s config.xml file (usually located in app/code/local/YourVendor/YourModule/etc), add a reference to the model:
<models>
<featuredproducts>
<class>YourVendor_FeaturedProducts_Model</class>
<resourceModel>featuredproducts_mysql4</resourceModel>
</featuredproducts>
<featuredproducts_mysql4>
<class>YourVendor_FeaturedProducts_Model_Mysql4</class>
<entities>
<bestseller>
<table>catalog_product_flat_1</table>
</bestseller>
</entities>
</featuredproducts_mysql4>
</models>
Finally, you can use the new model in your phtml file:
<?php
$_productCollection = Mage::getResourceModel('featuredproducts/bestseller')->addBestSelling();
?>
This approach allows you to encapsulate the collection logic within a separate class and reference it using Magento’s resource model system. However, it requires more setup compared to simply creating a custom block.
Conclusion
Creating reusable product collection blocks is a powerful way to keep your templates clean, promote code reuse across different parts of your store, and simplify maintenance tasks. By encapsulating the collection logic within a separate block or model, you can reduce duplication in your templates and make it easier to update or modify your collection criteria in the future.
Remember, the key to maintaining a well-organized Magento codebase is to keep related functionality grouped togetherâwhether that’s within blocks, models, or other custom components. If you find yourself repeatedly using similar logic across multiple parts of your store, consider refactoring it into a reusable component like we’ve demonstrated here.
For more advanced techniques in working with product collections and improving Magento performance, check out our guide on product collection optimization.
Happy coding!