Magento Factory Design Patterns

In Magento  “Factory Method” is used to instantiate classes . You instantiate a class in Magento by calling an appropriate method passing an abstract name representing a class group followed by a class name. Class groups and their appropriate abstractions are declared in your configuration XML files in your module’s /etc/ folder.

Model Abstraction

You declare a Model class group in your config.xml file with the following:

 

<config>
  <global>
    <models>
     <abstractname>
        <class>Namespace_Modulename_Model</class>
     </abstractname>
    </models>
  </global>
</config>

You can now call a new model from your Model folder by the method, Mage::getModel().

Example: Mage::getModel(‘abstractName/setup’);

This will call Namespace_Modulename_Model_Setup. Also, due to the autoload() method used in Magento, it will look for a file located in app//Namespace/Modulename/Model/Setup.php.

You can also call Mage::getSingleton(). The difference is that getSingleton() will use the Singleton Pattern, meaning that only on instantiation of a class is used at runtime. So if you call getModel(), you will create a new class every time, but if you call getSingleton(), it will only use the currently existing, (if any) instantiation of that class.

Block Abstraction

The same methods are used as Models when it commes to creating a class group for blocks.

 

<config>
  <global>
    <blocks>
     <abstractname>
        <class>Namespace_Modulename_Block</class>
     </abstractname>
    </blocks>
  </global>
</config>

 

You can instantiate a block class with a number of methods. You can call Mage::getBlockSingleton(), you can instantiate it through the layout xml (), or through createBlock(), addBlock(), and getBlock() located in Mage_Core_Model_Layout.

Helper Abstraction

Helpers are declared the same way as Models and Blocks.

 

<config>
  <global>
    <helpers>
     <abstractname>
        <class>Namespace_Modulename_Helper</class>
     </abstractname>
    </helpers>
  </global>
</config>

 

You can call a new helper class by using Mage::helper(‘abstractName’); If no file declaration is used, it is assumed that ‘Data’ is what is being called.

Example: Mage::helper(‘abstractName’) calls Namespace_Modulename_Helper_Data located in app//Namespace/Modulename/Helper/Data.php

 

For More About Design Patterns Click here

Leave a Reply

Your email address will not be published.