Magento Coding Issues Solution

By | January 4, 2014

From earlier post we have discuss about the commmon coding issues.so for that we have the solution for every parameters

1)Loops
Expensive operations, such as SQL queries and redundant computations within loops, are a common mistake which will affect the perfomrance.

For Example

for ($i = 0; $i < count($rows); $i++) {
//some code
}

Solution

$rowNum = count($rows);
for ($i = 0; $i < $rowNum; $i++) {
//some code
}

2)SQL Queries inside loop

Execution of an SQL query is one of the most computationally expensive operations. Running an SQL query in a loop will most probably result in a performance. Very often developers load Magento models in a loop.

For Example

foreach ($this->getProductIds() as $productId) {
$product = Mage::getModel(‘catalog/product’)->load($productId);
$this->processProduct($product);
}

Solution

 
$collection = Mage::getResourceModel(‘catalog/product_collection’)
->addFieldToFilter(‘entity_id’, array($this->getProductIds()))
->addAttributeToSelect(array(‘name’));
foreach ($collection as $product) {
$this->processProduct($product);
}

3) Models
Loading the same model same time which allow to call load() method again and again, one or more queries are ran against the database. Loading the same model several times causes noticeable performance degradation.

For Example

$name = Mage::getModel(‘catalog/product’)->load($productId)->getName();
$sku = Mage::getModel(‘catalog/product’)->load($productId)->getSku();
$attr = Mage::getModel(‘catalog/product’)->load($productId)->getAttr();

Solution

$product = Mage::getModel(‘catalog/product’)->load($productId);
$name = $product->getName();
$sku = $product->getSku();
$attr = $product->getAttr();

4) Collection

Magento collections provide a large set of operations to work with a set of models.Processing large data sets requires a lot of system and network resources, so it is extremely important to restrict the results by applying proper filters and limits, to avoid fetching and processing more data than necessary.

For Example

public function getRandomItem() {
$collection = Mage::getResourceModel(‘mymodule/my_collection’)-
>setRandomOrder();
return $collection->getFirstItem();
}

Solution

public function getRandomItem() {
$collection = Mage::getResourceModel(‘mymodule/my_collection’)-
>setRandomOrder()
->setPageSize(1);
return $collection->getFirstItem();
}

Hope now this make the Developer Work easy and will help you

Leave a Reply