Use of helpers in Magento for reducing the number of database queries

Helpers in Magento have one unique feature– they are singletons. It means that every call of  Mage::helper() – of course with the same class identifier, for instance Mage::helper(‘creativevariants’) – will return us the same object instance (in this case it will be Creativestyle_Variants_Helper_Data). This can be used for convenient storage of once downloaded data from the database, for later use in any part of the script. This method is completely transparent for helper’s user – the data are retrieved from the database during the first use and then stored inside the object.

Assuming that you want to have access to configurable and simple products, there is a simple helper you can write:

As you can see, the above helper stores two arrays – $parentId and $simpleIds, which respectively store parents identifiers and a list of related products. With this kind of helper, you can use its public methods anywhere script (also in *. Php as well as * . PHTML ) – query to the database will be processed only at the time of first use of the method, each subsequent call will return the data stored in the helper .

Example: Iteration through the collection.

The request will be sent only once, by the first time through the loop. What’s more, if in any other file within the same page load, one of the methods of this helper has already been called – there will be not one database query in the above loop. As mentioned earlier, a helper in Magento is a singleton and each time Mage :: helper () returns the same instance of the object (of course, with the same identifier helper ).

The given example refers to the relationship between the simple and configurable products. This method can be used for any data – for instance, for downloading related products (related products , upsell & crossell products), option attributes etc.

NOTE ! – The presented code gets all the links in the table at the same time. In the case of a large number of links between the products in the database, check if there is enough amount of memory limit available. In addition, the method makes sense when we have many configurable products within a single script execution and we often download linked variants for them.

The complete code module: Creativestyle_Variants.zip

pluswerk