27
May

We will be looking into some important methods used frequently in Magento like getModel(), getData(), getSingleton()..

getModel() (To create an instance of a Model class) :

The getModel() function is used to create an instance of a Model class. For example

$Product = Mage::getModel(’catalog/product’);

would basically tell Magento to create an instance of Mage_Catalog_Model_Product class. (ie. Mage/Catalog/Model/Product.php). If we now echo the get_class($Product) we would get the Mage_Catalog_Model_Product text displayed in our browser. You can use all methods defined in Product.php. Some useful methods include getName, getPrice, getTypeId, getStatus which we can execute like:

echo ‘Product name: ‘. $Product->getName();
echo ‘Product price: ‘ . $Product->getPrice();

However, the above code wont give you anything. You will not see any price displayed in the browser. This is because you haven’t loaded the product using load() method. We have to use the load method to load some data into our newly instantiated object.

$Product->load(53);

where 53 is the product id.

getData() (To get relevant data from the object instance)

This function is used to get relevant data from the object instance. Let’s say you want to retrieve the SKU value. You can use some other method for that like getSku() method that needs to be executed on object of Product type or you can:

echo $Product->getData(’sku’);

getData can be executed with or without any parameters passed to it. If you execute it without any parameters you get the array variable as a result. You can’t directly echo the array. You would have to map it to some field, like echo $arayVar['someField']. What are all the available fields? To find out you can do something like

echo ‘<pre>’;
print_r($Product->getData());
echo ‘</pre>’;

You can get the sku of the product by:

$ProductData = $Product->getData();
echo $ProductData->sku;

or:

echo $Product->getData(’sku’)

Another example:

$ProductData = $Product->getData();
$StockItem = $ProductData->stock_item;

Now your $StockItem variable is a object of type Mage_CatalogInventory_Model_Stock_Item and you can go ahead and use the same principle used until this point to find it’s methods and the data it holds.

First use the getModel to create the instance of object then you use getData to retrieve the data from that instance.

getSingleton():

One of the important architectural feature is it’s Singleton design pattern. In short, Singleton design pattern ensures a class has only one instance. Therefore one should provide a global point of access to that single instance of a class.

So when you are using getSingleton you are calling already instantiated object. So if you get the empty array as a result, it means the object is empty. Only the blueprint is there, but nothing is loaded in it.

Registry:

We had told that Magento provides global point of access to single instance of classes. How does Magento do it ?. This is done by using an array called registry in Mage.php.

Checkout the Mage.php file and you will see an array variable called _registry.

In order to provide global point of access for an instance of a class we must register the object into the registry array by using a function called register. For example:

Mage::register(’events’, new Varien_Event_Collection());
Mage::register(’config’, new Mage_Core_Model_Config());

Here is the code of the register() function:

public static function register($key, $value, $graceful = false)
{
if(isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
Mage::throwException(’Mage registry key “‘.$key.’” already exists’);
}
self::$_registry[$key] = $value;}

Basically what it does it registers an object with name as $key and the instance as $value into the registry array. You can also unregister an object using the unregister() function.

Whenever we want to call an object from the registry we use the registry() function. For example in the getConfig() method:

public static function getConfig()
{
return Mage::registry(’config’);
}

Previously we had registered an  instance of Mage_Core_Model_Config as ‘config’. The getConfig() function returns that instance. Here is the code for registry() function:

public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}

Analyzing the getModel() and getSingleton() code:

The getModel() and getSingleton() functions works by using this registry. Here is the code for the getModel() function:

public static function getModel($modelClass=”, $arguments=array())
{
return Mage::getConfig()->getModelInstance($modelClass, $arguments);
}

Basically it gets the Config object (This object is formed by parsing all the config.xml files, so it contains all config details of all moules) and then makes an instance of the model that is specified by the $modelClass argument.(for example if $modelClass is ‘catalog/product it creates an instance of Mage_Catalog_Model_Product)

Now take a look at the getSingleton Method:

public static function getSingleton($modelClass=”, array $arguments=array())
{
$registryKey = ‘_singleton/’.$modelClass;
if (!Mage::registry($registryKey)) {
Mage::register($registryKey, Mage::getModel($modelClass, $arguments));
}
return Mage::registry($registryKey);
}

Basically it checks wheter an instance of that class is already existing, if so return that instance else create a new instance and register it as ‘_singleton/$modelClass’.

Govind Krishna
Posted by on 27 May 2009 by Govind Krishna in Magento eCommerce Tips

8 Responses to “Some Important Functions: getModel(), getData(), getSingleton()”

  • Mke

    Hello, good post it helped me understand the architecture a little bit better. I am trying to display category id’s in my search results. With that said I was able to find the function getCategoryId and call it like this:

    $Product = Mage::getModel(‘catalog/product’);

    echo $Product->getCategoryId();

    With that said, this will pull up the category id in grid view in the, however it disappears in search results. How can identify what models can render what?

  • Thanks Govind Krishna for this useful post.

  • Hey, really useful post Govind. This has really helped me understand some of the fundamentals of Magento classes and what methods are available to use.

    Thanks!

  • Thanks for the breif introduction on magento core function which will be very helpful in development

  • Shahedah

    Thanks,its really beneficial.Thanks a lot.

  • Shahedah

    For a php beginner its really not too easy to understand Magento’s structure at once.But with such information it becomes easy to do so.

  • saumil

    thanks for post this article it help me know magento litel bit more

Add reply

*