Good morning, everyone! I am Alex. Today, I’d like to discuss Functional and Factory class groups in Magento. This post is very helpful for you so please keep reading.
As you know Magento is built based on module architecture, which leads to the requirement that there must be an interaction between modules. Hence, in this part we will learn about the way these modules used.
I. Definition and Examples of functional class & factory class
1. Functional Class:
- Class: only contains functions and static attributes? (not sure)
- For example: Mage
2. Factory Class:
- Class: consists of functions to create the instance (object) of different Classes. Class depends on input parameters
- For example: class Mage
– Create an instance of class Mage_Catalog_Model_Product
– Generate an instance of class Mage_Catalog_Block_Product_View
II. Definition of Instance, the ways to create the instance object in Magento
- Definition : In OOP, Instance is an Object
- Create an instance object in Magento
Mage::getModel(‘catalog/product’); Mage::getBlockSingleton(‘catalog/product_view’); Mage::app()->getLayout()-createBlock(‘catalog/product_view’)
- The process to generate an instance through the function Mage::getModel() is as below:
- 1) Call function getModel() trong class Mage
- 2) Call function getModelInstance() in class Mage_Core_Model_Config
- 3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.
- 4) Add a new object by the New command:
$obj = new $className($constructArguments);
In this example, $className = ‘Mage_Catalog_Model_Product’
- Get different instances from different places:
- – With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).
- – Function Mage::getSingleton() always gives only one object (instance) back.
III – Study Singleton Pattern
Singleton Pattern makes sure that each Class has a unique Instance. You can use a Global Point to access that Instance (=> it is possible to call Instance anywhere). Mage::getSingleton(‘checkout/cart’) – This function always returns only one Cart object although you call it anywhere.
IV – Question
Question: According to the following command, please define the value printed?
$productA = Mage::getSingleton(‘catalog/product’)->load(9); $productA->setPrice(100); $productB = Mage::getSingleton(‘catalog/product’); $productB->setPrice(200) echo $productA->getPrice(); echo $productB->getPrice();
Answer: Print the “200” two times.
Well, this article ends here. I really hope your feedback of the post, so please feel free to leave comment on our Blog.