Skip to main content

[magento] Create a new controller

MAGENTO MODULE: CREATE YOUR OWN CONTROLLER

Respect my authoritahMagento is based on MVC model. This model helps for defining models, view (layout + templates) and controllers. Despite big amount of modules available by default in Magento and on Magento Connect, you may want to create your own module and define your controller for you Magento website. No problem, this tutorial will explain you how to create your own controller and how to make it respect its authoritah to layouts and templates.
Purpose of this example controller will be to give result of two integers multiplication (very useful if you lost your calculator). Integers will be provided through a basic form. Result will be displayed in a Magento notification.
Before starting creation of your module, please turn off the cache management in order to see immediately every change.

Creating your module

Our extension will be named arithmetic. Folders needed for this extension are created.
$ mkdir -p app/code/local/Baobaz/Arithmetic/controllers
$ mkdir -p app/code/local/Baobaz/Arithmetic/etc
We create file app/code/local/Baobaz/Arithmetic/etc/config.xml, in order to register this extension
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <baobaz_arithmetic>
            <version>0.0.1</version>
        </baobaz_arithmetic>
    </modules>
</config>
And a file app/etc/modules/Baobaz_Arithmetic.xml for its activation:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Baobaz_Arithmetic>
            <active>true</active>
            <codePool>local</codePool>
        </Baobaz_Arithmetic>
    </modules>
</config>
For more informations about creation of a new extension, please check Wojtek's post "Developing module for Magento Tutorial - Where to Begin [Part 1]".

Creating a controller

You need now to create file app/code/local/Baobaz/Arithmetic/controllers/IntegerController.php and write method that will be used for multiplication.
Controller files must always follow pattern xxxxxController.php (xxxxx will be used after in url for calling this controller) and put in controllers folder. 
Controllers methods names must follow pattern yyyyyAction (yyyyy will also be used in url for calling this controller). For the moment content of our file is:
class Baobaz_Arithmetic_IntegerController extends Mage_Core_Controller_Front_Action
{
    public function multiplyAction(){
    }
}
We need to indicate now that some controllers are available in Arithmetic modules. For doing that, we add the following content in app/code/local/Baobaz/Arithmetic/etc/config.xml file:
<config>
    ...
    <frontend>
        <routers>
            <arithmetic>
                <use>standard</use>
                <args>
                    <module>Baobaz_Arithmetic</module>
                    <frontName>arithmetic</frontName>
                </args>
            </arithmetic>
        </routers>   
    </frontend>
</config>
Let see how this router declaration works:
  • <frontend> indicates that router will be use in front part of website
  • <routers> is where you declare all your routers
  • <arithmetic> is identifier of this router
  • <use>standard</use> can take value standard (for front part) or admin (for admin part).
  • <module>Baobaz_Arithmetic</module> indicates which module contain controller that handles this router
  • <frontName>arithmetic</frontName> is router name that will be used in url
We can now modify multiplyAction method for making it displaying a message:
public function multiplyAction(){
    echo "Respect my authoritah";
}
When you call now url http://monsitemagento/arithmetic/integer/multiply message "Respect my authoritah"will be displayed. Let dissect this url:
  • arithmetic tells that controller is in Baobaz_Arithmetic module
  • integer tells that controllers/integerController.php file must be cehcked
  • multiply tells that multiplyAction method must be chosen in this file

Displaying a template

We define which layout file will be used in the module:
<config>
    ...
    <frontend>
        ...
        <layout>
            <updates>
                <arithmetic>
                    <file>arithmetic.xml</file>
                </arithmetic>
            </updates>
        </layout>
    </frontend>
</config>
We create app/design/frontend/default/default/layout/arithmetic.xml file in order to define which blocks will be used forcontroller that was just made.
<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <arithmetic_integer_multiply>
        <reference name="root">
            <action method="setTemplate">
                <template>page/1column.phtml</template>
            </action>
        </reference>
        <reference name="content">
            <block type="core/template" name="arithmetic_integer_multiply" template="arithmetic/integer/multiply.phtml"></block>
        </reference>
    </arithmetic_integer_multiply>
</layout>
Main template used by arithmetic/integer/multiply is page/1column.phtml. For "content" part of this template, onlyarithmetic_integer_multiply block will be displayed. This block does not need any particular management. It is then set withcore/template type that is default type. Template file used will be arithmetic/integer/multiply.phtml.
Our template is defined, app/design/frontend/default/default/template/arithmetic/integer/multiply.phtml must then be created. This file will be empty for the moment..
For displaying correctly layout, it must be loaded in controller
public function multiplyAction(){
    $this->loadLayout();
    $this->renderLayout();
}

Interaction between template and controller

Our template will just have a basic form for providing integers to multiply
<form action="<?php echo Mage::getUrl('arithmetic/integer/multiply') ?>" method="post">
    <fieldset>
        <ul>
            <li>
                <label for="int1">Integer 1</label>
                <input type="text" id="int1" name="int1" />
            </li>
            <li>
                <label for="int2">Integer 2</label>
                <input type="text" id="int2" name="int2" />
            </li>
            <li><input type="submit" value="Multiply" /></li>
        </ul>
    </fieldset>
</form>
Action form url is again arithmetic/integer/multiply. Controller action must then be modified in order to manage data from form and to give result.
public function multiplyAction(){
    if ($this->getRequest()->isPost()){
        $int1 = $this->getRequest()->getPost('int1');
        $int2 = $this->getRequest()->getPost('int2');
        $result = $int1 * $int2;
    Mage::getSingleton('customer/session')->addSuccess("$int1 * $int2 = $result");
    }
    $this->loadLayout();
    $this->_initLayoutMessages('customer/session');
    $this->renderLayout();
}
In order to know if controller is called after using form, following instruction is used:
$this->getRequest()->isPost()
Result is put in 'customer/session' session. For being able to display this result in template, message template must be loaded in multiplyAction method:
$this->_initLayoutMessages('customer/session');
Add then in you template the following line where you want to display the result
echo $this->getMessagesBlock()->getGroupedHtml();
And here we are: we have now a new controller that displays result of a multiplication.
All files used in this tutorial are available in baobaz_arithmetic.tar.gz archive.
This post was inspired by Alan Storm's post Magento Front Controller. Take a look at his very interesting blog.

Comments

Popular posts from this blog

Browser User Agent List

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0 Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0;...

[linux] Adjusting child processes for PHP-FPM (Nginx)

Adjusting child processes for PHP-FPM (Nginx) Problem: The following warning message appears in the logs: [26-Jul-2012 09:49:59] WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawning 32 children, there are 8 idle, and 58 total children [26-Jul-2012 09:50:00] WARNING: [pool www] server reached pm.max_children setting (50), consider raising it It means that there are not enough PHP-FPM processes. Solution: We need to calculate and change these values based on the amount of memory on the system: /etc/php-fpm.d/www.conf pm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 35 - the following command will help us to determine the memory used by each (PHP-FPM) child process: ps -ylC php-fpm --sort:rss The RSS column shows non-swapped physical memory usage by PHP-FPM processes in kilo Bytes. On an average each PHP-FPM process took ~75MB of RAM on my machine. Appropriate valu...

[symfony] Assert in Entity

* @Assert\NotBlank() * @Assert\Blank() * @Assert\NotNull() * @Assert\Null() * @Assert\True(message = "The token is invalid") * @Assert\False( *     message = "You've entered an invalid state." * ) * @Assert\Type(type="integer", message="The value {{ value }} is not a valid {{ type }}.") is_ array bool callable float double int integer long null numeric object real resource scalar string ctype_ alnum alpha cntrl digit graph lower print punct space upper xdigit * @Assert\Email( *     message = "The email '{{ value }}' is not a valid email.", *     checkMX = true * ) * @Assert\Length( *      min = 2, *      max = 50, *      minMessage = "Your first name must be at least {{ limit }} characters long", *      maxMessage = "Your first name cannot be longer than {{ limit }} characters long" * ...