miercuri, 24 noiembrie 2010

Misuse of helper classes in Magento?

In its MVC structure, Magento allows you to throw in additional classes that might not fit in strictly under the MVC “letters”. One example of these classes are helper classes. These are usually used to isolate a certain, possibly useful, algorithm. Algorithm whose usage would be overhead to write a model as it is more static and general in nature, meaning there is no point in applying it to given instance of an object.

Calling a helper class from almost anywhere in your PHP code is extremely easy.

$helper = Mage::helper('catalog');//which is same as$helper = Mage::helper('catalog/data');

Most helpers in Magento inherit from Mage_Core_Helper_Abstract class, which by itself has several “different responsibility” methods implemented.

If you remove the fancy “helper” name out of the context of thinking, helper is just a class like any other on OOP. So, how do helper classes conform to the 5 principles of class design within the paradigm of object oriented programming?

Witouth going to deep into this, I would like to point out single example/principle that caught my eye.

The SingleResponsibilityPrinciple among other things states: each responsibility should be a separate class, because each responsibility is an axis of change.

Let take a look at Magento’s core helper classes like app/code/core/Mage/Core/Helper/Data.php, where you have methods like formatPrice($price, $includeContainer = true), xmlToAssoc(SimpleXMLElement $xml), getStoreId($store=null), etc. Clearly this breaks the “each responsibility should be a separate class” logic.

This however does not play any significant role in your Magento development as one can look at helper classes simply as “place it here if you do not know where”. My reason of mentioning the above is to simply point out some paths one can consider when giving the “Magento is designed good/bad” statements.

Depending on the way you use them, helper classes can be truly useful. For example, code reuse in a company modules. Lets say a company has a certain policy on how its modules will behave in certain situations and what information they will share across various modules, etc. This is where you can throw in bunch of mini task helper functions/methods that do not seem to fall under any strict model definition, but preferably each helper class with its own subset of methods.

On the other hand, they can turn out to be a real mess of spaghetti code leading to bad application/module design. Seems like in Magento development it usually comes down to how much time you have on hand.

So, final questions: Are Magento helper’s good or bad thing? Where do you draw the line between block/view or model “level” helpers?

Looking forward to your replies.

Cheers.

To post code in comments, place your code inside [code] and [/code] tags.


View the original article here

Niciun comentariu:

Trimiteți un comentariu