Saturday, November 28, 2009

Use of getModel and getData methods

getModel

See the code below:
$model = Mage::getModel(‘catelog/product’);
Let me explain the things, basically we have created an instance of Mage_Catelog_Model_Product class.

This means that our $model variable is actually an instance of Mage_Catalog_Model_Product class. This matches the class name contained inside the app/code/core/Mage/Catalog/Model/Product.php file. Inside this Product.php file we can clearly see that Mage_Catalog_Model_Product class extends the Mage_Catalog_Model_Abstract class. What this means is that our $model can use all of the methods (functions) declared inside the Mage_Catalog_Model_Product class plus those declared inside the Mage_Catalog_Model_Abstract class.

To iterate and echo out the available method names like
echo ‘<ul>’;
foreach (get_class_methods(get_class($model)) as $method) {
echo ‘<li>’ . $method . ‘</li>’;
}
echo ‘</ul>’;

Now you can see lot of userful methods like getName, getPrice, getTypeId, getStatus which we can execute on our $model variable like

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

The above will not show anything, what you have to do is call the load function as follows before above code.

$model->load(13); 

getData

getData is just one of multiple available methods for $model. 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.

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

Now if you want to get product name or price, you can use getData method as below.

echo $model->getData(’sku’);
or
$modelData = $model->getData();
echo $modelData->sku;

Now from above discussion you come to know how to use getModel and getData methods.

No comments:

Post a Comment