Pages

Friday, 20 June 2014

Magento Developper’s Guide (Lesson 4) – The Model and the database

This tutorial is the 4th of many , if you do have not already done this, i suggest you to read the previous tutorials and to start at the summary of this series.

We have previously created a plugin with a controller, a block and its associated template. Our plugin works well and I think now you understand how it works. I take the opportunity to thank you for your very positive feedback that motivate me to continue this series of tutorials.

Now, a plugin that is the equivalent of a echo is not very useful and it has nothing very complicated as you have seen. In this tutorial we will modify our plugin to look for data in our database (in MySQL) and display it in our Block.

Step 1: Create the table

We will say that our plugin is an address book, we want the block to display all the book addresses one after the other of the form:
Name Surname telephone_number

Example:
John Smith 0000000000
John Smith 0000000000
John Smith 0000000000
John Smith 0000000000


We will start by creating a table in the database, we will call this table Easylife_test
So execute the following query:

CREATE TABLE `magento`.`Easylife_test` (
`id_Easylife_test` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `nom` VARCHAR( 50 ) NOT NULL ,
 `prenom` VARCHAR( 50 ) NOT NULL ,
 `telephone` VARCHAR( 20 ) NOT NULL
);
Your table is now in the database. To interact with it, we’ll create the model.

Step 2: Declare the model in config.xml

You know, Magento use the MVC model, it is necessary to create a model in order to interact with our database.

To create a template, you who have followed the previous three tutorials …what are we going to have to do? You have the answer comes out automatically from your head as you start to get used to ^ ^, we will first declare the model in the config.xml file of our plugin.

Go therefore etc/config.xml and add in <global> after the declaration <blocks> :



<models>
<test>
     <class>Easylife_Test_Model</class>
     <resourceModel>test_resource</resourceModel>
 </test>
<test_resource>
     <class>Easylife_Test_Model_Resource</class>
     <entities>
         <test>
           <table>easylife_test</table>
         </test>
      </entities>
</test_resource>
</models>
    <!-- allow the plugin to read and write -->
<resources>
        <!-- connection to write -->
        <test_write>
            <connection>
                <use>core_write</use>
            </connection>
        </test_write>
        <!-- connection to read ->
       <test_read>
          <connection>
             <use>core_read</use>
          </connection>
       </test_read>
</resources>
 <!-- -/- -->


In :

It says here that the model classes wills be in the directory app/code/local/easylife/Test/Model/ and the « resource » that is to say the thing used to collect data for the model will be defined by test_resource defined in the classes will be in app/code/local/Easylife/Test/Model/Resource/ and an entity test represent the table easylife_test we have created earlier in the database.

Step 3: Create the Model

Once your Model declared, you can now create the files. So create the following three files:
app/code/local/Easylife/Test/Model/
app/code/local/Easylife/Test/Model/Resource/
app/code/local/Easylife/Test/Model/Resource/Test/
Then, in app/code/local/Easylife/Test/Model/ create a file Test.php which will contain the following code:


<?php
class Easylife_Test_Model_Test extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('test/test');
    }
}


This is your test model, you are telling that there’s a logical entity test of your plugin test .
Then go to the folder app/code/local/Easylife/Test/Model/Resource/ and create a file Test.php which will contain:


<?php
class Easylife_Test_Model_Resource_Test extends Mage_Core_Model_Resource_Db_Abstract
{
    public function _construct()
    {
        $this->_init('test/test', 'id_easylife_test');
    }
}


This is where you specify your model, a Magento test/test will use as primary key the id_easylife_test . (Be careful that this field is in auto increment and is the primary key of your table.

Then go to the folder app/code/local/Easylife/Test/Model/Resource/Test/ and create a file Collection.php which will contains:


<?php
class Easylife_Test_Model_Resource_Test_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('test/test');
    }
}


This file is used to define the model for your collection test/test. You ‘re maybe not very well understanding what all this is, it is imperative that you to memorize these steps to create a template in Magento. Once these files are created, you can use your model to interact with your tables very easily.

Step 4: List contacts in our Block

Remember, in the preceding tutorial we have created a block in app/code/local/Easylife/Test/Block called Myblock.php . We will change that block to display the contact list in the database. First, insert few lines in your database table easylife_test . Then change your Myblock.php as follows

<?php
class Easylife_Test_Block_Monblock extends Mage_Core_Block_Template
{
    public function mythodblock()
    {
        //return 'information about my block !!' ;
        //on initialize la variable
        $retour='';
        /* we are doing the query to select all elements of the easylife_test table (thanks to our model test/test and we sort them by id_easylife_test */
        $collection = Mage::getModel('test/test')->getCollection()
            ->setOrder('id_easylife_test','asc');
        /* then, we check the result of the query and with the function getData() */
        foreach($collection as $data)
        {
            $retour .= $data->getData('nom').' '.$data->getData('prenom')
                .' '.$data->getData('telephone').'<br />';
        }
        //i return a success message to the user thanks to the Session.
        Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');
        return $retour;

       
    }
}

Looking at the code, I think you’ll understand what we did with comments, if this is not the case feel free to leave a comment. Now test your code by going to yoursite.com/test/index and you’ll see your contact list.

Your homeworks:

Try to repeat this and make a plugin from scratch before starting the next tutorial, you need to know to how to do the 4 firsts tutorials « fingers in the nose » before starting the next tutorial. Practice for exemple in making a new plugin to manage your movie library. It strongly resembles to what we’ve done, but it’s different so you’ll be able to practice and really understand what you are doing.

End of this tutorial

Here is the end of this tutorial, I hope this tutorial helps you, you now know to interact with the database in your Magento extensions. Feel free to leave comments if you have any questions or comments.


 
Find the summery of this tutorial

No comments:

Post a Comment