If you are developing in Magento, sooner or alter you will need to obtain some information from database. This article will show you how to retrieve almost anything using getModel, getData and getter methods in general.
For an example, let say you are trying to retrieve products name, description and price. First thing you will need to do, is get products model:
$productModel = Mage::getModel('catalog/product');
By calling getModel(‘catalog/product’) you will get instance of Mage_Catalog_Model_Product class, defined in app/code/core/Mage/Catalog/Model/Product.php. But how does Magento know where to look for for class?
Well, first part of parameter ‘catalog/product’ comes from modules configuration, and is usually the same as name of module folder. If you take a look at app/code/core/Mage/Catalog/etc/config.xml, you will see:
<config> … <global> <models> <catalog> <class>Mage_Catalog_Model</class> … </catalog> … </models> … </global> … </config>
From here, you can see that all model whose name begins with Mage_Catalog_Model are defined within Model folder of this module. Second part of ‘catalog/product’ is telling Magento in which file is class defined. And in this case, it is Product.php.
Now that we have right model, next step would be to tell our model, which product should be loaded. This is done easily with load($id) method:
$product = $productModel->load(42);
Just to note here, 42 to is an example of id, and it should be replaced with id of product you are trying to load.
Now that we have loaded our product, there are two ways of retrieving data from object:
$name = $product->getName(); // same as $product->getData('name'); $description = $product->getData('description'); // same as $product->getDescription();
Both of them will work perfectly fine. But, when it comes to price, it’s a little bit different:
$price = $product->getPrice(); // same as $product->getData('price'); $finalPrice = $product->getFinalPrice();
In case that our product falls under any of price rules, those two variables would have different value. What is the difference? Variable $price would have products base price, visible from administration when you edit product. Variable $finalPrice, in this case, would have price with processed price rules.
Hope some of you find this useful. Feel free to provide some feedback.