Given the sheer size of Magento system, its quite easy to loose valuable time when trying to achieve even the basic things like “Creating simplest ORM model class”. Substantial amount of serious programming in Magento requires you to write some values to database.
By now, most of us have seen how “cool” Magento models are, and how “easy” it is to write values to models by using syntax like
//$someModel = new Company_Modul_Model_SomeModel(); //or the preferable way $someModel = Magent::getModel('company/somemodel'); /* To use some existing model record from database */ //$someModel->load(); /* Some valid id in database */ //$someModel->setSomeField = 'Some value'; //or the preferable way $someModel->setSomeField('Some value'); //Save model $someModel->save();
Code example shown above is clean, easy to use, etc. Probably the main thing to note is the usage of “$someModel->someField = ‘Some value’;” or “$someModel->someField(Some value);”. Safest, and more “cooler” way would be to assign field values trough “virtual methods” like “$someModel->someField(Some value);”. By doing so you are preparing a “safe ground” for yourself for possible latter modifications on individual fields (attributes) of model before “save” operation.
Lets say you wish to parse some logic on certain field before its set, in that case its easier to do “$someModel->someField(Some value);” and later implement the actual “someField()” method inside the model that handles the necessary logic.
Hopefully you catch my point 🙂
Moving along, the model itself. To get the model class to behave like the one shown above, you need to implement it in the proper way.
Attached is a sample module, that does exactly that. All you need to do is un-archive it, copy-paste the /app folder to your demo store, and refresh the demo store home page.
Module creates database table called “ajzele_hello” and appropriate “installation mark” entry in core_resource table called “hello_setup“.
Once you refreshed your home page, you should be able to do something like:
//$model = new Ajzele_SimpleModel_Model_Hello(); $model = Mage::getModel('hello/hello'); $model->setField1('Branko'); $model->setField2('Ajzele'); $model->save();
This should make a new entry in the database table “ajzele_hello”.
Note, DO NOT USE this module on live site. This is merely for educational purposes. As much as I can confirm that module is essentially simple and it works out of the box, I do not wish to comment on any “it broke my site” replies.