Use of getModel in magento:
In magento, if you check any of the model file (not only model, other files also), you will see the below code like
Mage::getModel(“mymodule/mymoduleclassfilename”).
Based on the above code, we will get entire detail about that particular module database information from DB. We will retreive the information from DB by based on primary key, or entire collection of table, or filter by some condition.
How it is working in magento:
Once declared the above the code, the magento running time, it look the configuration file (xml file) and then come to know where the flow will call next. Here, “mymodule” is nothing but, its our module name. “mymoduleclassfilename” is nothing but, its our class file name.This mapping and all done from xml file.
Ex:
<global>
<models>
<mymodule>
<class>Jute_Mymodule_Model</class>
<resourceModel>mymodule_mysql4</resourceModel>
</mymodule>
<mymodule_mysql4>
<class>Jute_Mymodule_Model_Mysql4</class>
<entities>
<mymoduleclassfilename><table>MyCustom_Master_Table</table></mymoduleclassfilename>
</entities>
</mymodule_mysql4>
</models>
…
</global>
How we can declare the table:
1. Create first “Custom table” with magento sql code from below code (if your trying create first time then install file, else upgrade file)
Mymodule/sql/mymodule_setup/mysql4-install-0.1.0.php
2. Cleare cache and check your DB. “MyCustom_Master_Table” table will create in your DB.
3. Refer above xml code now,
“<mymoduleclassfilename><table>MyCustom_Master_Table</table></mymoduleclassfilename>”.
Here, we are mapping our Table into “mymoduleclassfilename” file class. So what and all function you wrriten into this file, we can use those function like below way
Mage::getModel(“mymodule/mymoduleclassfilename”)->getMyfunction();
But before , we use this above function we have to declare the table and method like as below file structure
4. Jute/Mymodule/Model/mymoduleclassfilename.php
class Jute_Mymodule_Model_mymoduleclassfilename extends Mage_Core_Model_Abstract
{
public function __construct()
{
$this->_init(‘mymodule/mymoduleclassfilename’);
}
}
5. Jute/Mymodule/Model/Mysql4/mymoduleclassfilename.php
class Jute_Mymodule_Model_Mysql4_mymoduleclassfilename extends Mage_Core_Model_Mysql4_Abstract
{
protected function _construct()
{
$this->_init(“mymodule/mymoduleclassfilename”,”entity_id”);
}
}
Here “entity_id” is primary key of “Master table”
6. Declare collection file.
class Jute_Mymodule_Model_Mysql4_mymoduleclassfilename_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
protected function _construct()
{
$this->_init(‘mymodule/mymoduleclassfilename’);
}
}
7. Thats it. You module and table declaration is ready to use. Now you use whereever you want to call getModel(‘mymodule/mymoduleclassfilename’). You can do.