Creating a Magento Extension II

In this second part of the tutorial we present how to create a very basic model in the Magento module created in the first part.

So far we have reduced our module exclusively to the controller, as our business logic is really trivial and used as a simple print view on the page. The next step is to place the business logic (even if it is extremely simple) in a model and finally add a view.

The creation of the model is done in much the same way as we created the controller. First, we must indicate in the configuration file /app/local/Brainsins/Holamundo/etc/config.xml where Magento should look for the models, for this we must modify this file as shown below:

/app/code/local/Brainsins/Holamundo/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Brainsins_Holamundo>
            <version>0.1.0</version>
        </Brainsins_Holamundo>
    </modules>
    <frontend>
        <routers>
            <holamundo>
                <use>standard</use>
                <args>
                    <module>Brainsins_Holamundo</module>
                    <frontName>holamundo</frontName>
                </args>
            </holamundo>
        </routers>
    </frontend>
    <global>
        <models>
            <holamundo>
                <class>Brainsins_Holamundo_Model</class>
            </holamundo>
        </models>
    </global>
</config>

With this we are telling Magento, through the class tag, that our models are located in the path /Brains/Holamundo/Model. The path also starts with /app, like all modules, and continues in local/, as this is specified in the activation file.

Our class that will act as a model, remembering the relation between the file path and its name, will be called “Brainsins_Holamundo_Model_NombreDeLaClase”, in our case we will call it “Saludador”.

/app/code/local/Brainsins/Holamundo/Model/Saludador.php

class Brainsins_Holamundo_Model_Saludador extends Mage_Core_Model_Abstract {
    public function _construct() {
        parent::_construct();
        $this-&gt;_init('holamundo/saludador');
    }
 
    public function construirSaludo($nombre) {
        return 'hola ' . $nombre . '!';
    }
}class Brainsins_Holamundo_Model_Saludador extends Mage_Core_Model_Abstract {
    public function _construct() {
        parent::_construct();
        $this->_init('holamundo/saludador');
    }
 
    public function construirSaludo($nombre) {
        return 'hola ' . $nombre . '!';
    }
}

In this tutorial we will simply provide the model with functionality, but not state (you will not be able to save instances of it in the database, we will leave this for later). To be able to use this functionality from anywhere in Magento we will use the following code:

Mage::getSingleton('holamundo/saludador');

It is time to apply these changes to our controller:

/app/code/local/Brainsins/Holamundo/controllers/IndexController.php

<?php
class Brainsins_Holamundo_IndexController extends Mage_Core_Controller_Front_Action {
    public function indexAction() {
        echo("Hola Mundo!");
    }
 
    public function saludarAction() {
        $input = $this->getRequest()->getParam("nombre");
        $name = $input ? $input : "Desconocido";
        $saludador = Mage::getSingleton('holamundo/saludador');
        $saludo = $saludador->construirSaludo($name);
        echo($saludo);
    }
}

In this third part we will see the remaining component of the MVC: how to create a view. In the previous parts we got as a result of our extension text messages appearing on a blank page, now we will incorporate those messages into the Magento page structure.

We continue with the example of the “holamundo” extension that greets the visitor. Initially, the controller should be in charge of telling the model to build a greeting and then the view would request that greeting from the model and display it. However, let’s remember that, for simplicity’s sake, our model is stateless, so the view will not communicate with the same instance of the model as the controller. Therefore, in this tutorial, the calls we made before from the controller will now be made by the view. Later I will publish another advanced tutorial on how to create models.

The first thing we will do is to create a block. To do this, we will create the following file:

/app/code/local/Brainsins/Holamundo/Block/Holamundo.php

With the following code:

<?php
class Brainsins_Holamundo_Block_Holamundo extends Mage_Core_Block_Abstract {
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    protected function _toHtml() {
        $input = $this->getRequest()->getParam("nombre");
        $name = $input ? $input : "Desconocido";
        $saludador = Mage::getSingleton("holamundo/holamundo");
        return "<h1>" . $saludador->construirSaludo($name) . "</h1>";
    }
}

As you can see, this is pretty much the same code as in the controller in the previous tutorial, except that we no longer print anything on the page using PHP’s “echo” function. When we tell Magento to embed our block on the page, it will get the text to display using the _toHtml() function we have implemented.

To tell Magento that this new block exists, we first need to create a layout file for our extension. The layout file gives Magento information about which blocks to display in our extension, where they are placed and how they have to be displayed. In our case we just need to incorporate the block we have created into the content of the page.

/app/design/frontend/base/default/layout/holamundo.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <default></default>
    <holamundo_index_index>
        <reference name="content">
            <block type="holamundo/holamundo" name="holamundo" />
        </reference>
    </holamundo_index_index>
 
    <holamundo_index_saludar>
        <reference name="content">
            <block type="holamundo/holamundo" name="holamundo" />
        </reference>
    </holamundo_index_saludar>
</layout>

As you can see, we have created two identical entries, one for the index action and one for the greet action. Later we will change one of the two to show another way of creating views. Next we are going to indicate to Magento both the existence of blocks in our extension (the path where it can find them) and the existence of this layout file. This is done in the config.xml file.

/app/code/local/Brainsins/Holamundo/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Brainsins_Holamundo>
            <version>0.1.0</version>
        </Brainsins_Holamundo>
    </modules>
    <frontend>
        <routers>
            <holamundo>
                <use>standard</use>
                <args>
                    <module>Brainsins_Holamundo</module>
                    <frontName>holamundo</frontName>
                </args>
            </holamundo>
        </routers>
        <layout>
            <updates>
                <holamundo>
                    <file>holamundo.xml</file>
                </holamundo>
            </updates>
        </layout>
    </frontend>
    <global>
        <models>
            <holamundo>
                <class>Brainsins_Holamundo_Model</class>
            </holamundo>
        </models>
        <blocks>
            <holamundo>
                <class>Brainsins_Holamundo_Block</class>
            </holamundo>
        </blocks>
    </global>
</config>

Finally, as we have incorporated in the view the code we had in the controller, we have to change the controller. In addition, it will be the controller that will indicate to the view that it should be shown. With these additions, the controller code looks like this:

/app/code/local/Brainsins/Holamundo/controllers/IndexController.php

<?php
class Brainsins_Holamundo_IndexController extends Mage_Core_Controller_Front_Action {
    public function indexAction() {
        $this->loadLayout();
        $this->renderLayout();
    }
    public function saludarAction() {
        $this->loadLayout();
        $this->renderLayout();
    }
}

The disadvantage of this way of creating the views is that when we want to change some of the content of our extension (and this part is the most likely and frequently changed), we will have to change the code of the block. This problem is solved by creating another type of block that is not in charge of displaying the content of the view, but is associated with a template – a file that will directly contain the php and html code that will compose the content that we want to appear in the block.

Leave a Reply

Your email address will not be published. Required fields are marked *