The Factory Method is used to instantiate classes in Magento. 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:
1 2 3 4 5 6 7 8 9 |
<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/code/{codePool}/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.
1 2 3 4 5 6 7 8 9 |
<config> <global> <blocks> <abstractname> <class>Namespace_Modulename_Block</class> </abstractname> </blocks> </global> </config> |
The main way to instantiate a block is through:
1 |
Mage::app()->getLayout()->createBlock(); |
Helper Abstraction
Helpers are declared the same way as Models and Blocks.
1 2 3 4 5 6 7 8 9 |
<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/code/{codePool}/Namespace/Modulename/Helper/Data.php
Very Clear !!!! Thanks
Though it’s not “enough” expanded as mentioned above – i do think it give a proper explanation about factory method in magento
Thanks for the articles 😉
I think you should write about helpers other than default Data helper, for example Mage::helper(‘abstractName/another’); located in app//Namespace/Modulename/Helper/Another.php.
Another usefull info will be information about placing for example models in deeper directory e.g. app//Namespace/Modulename/Model/Install/Setup.php, Mage::getModel(‘abstractName/install_setup’). I think This is important thing for factory.
It looks like you covered a lot of it here 🙂
I will see about expanding and updating my articles at a later date.
Thanks for reading!