Today we will understand what is a controller in Magento and how to create it.
I hope you understand the MVC design pattern of Magento. Click here to see an introduction.
First of all, create a module. Click here to see the steps.
Now, create a folder named controllers under the Basic folder ( if you followed my create module post )
Now create a new PHP file FirstController.php inside the controllers folder with the following code:
<?php class Test_Basic_FirstController extends Mage_Core_Controller_Front_Action { public function indexAction() { echo "Hello from first controller"; } }
*Note:
We should understand the naming conventions of Magento.
Magento understands following naming conventions for controllers and methods:
- All controller files must have Controller.php after the name, hence FirstController.php
- All methods that represents a URL must have Action at the end, hence indexAction
- The name of the class must be like Namespace_Modulename_YournameController, hence Test_Basic_FirstController
Next, we need to define this controller in our modules configuration file. Add following lines in the etc\config.xml file-
<?xml version="1.0" ?> <config> <modules> <Test_Basic> <version>1.0</version> </Test_Basic> </modules> <frontend> <routers> <basic> <use>standard</use> <args> <module>Test_Basic</module> <frontName>custom</frontName> </args> </basic> </routers> </frontend> </config>
The <frontend> node here defines all the changes that we are going to make in the user area of the website.
The <routers> node is used to define the controllers of our module.
We can use any name instead of <basic> but it is advised to use module name to avoid confusions.
In the <args> section, we are telling Magento that the module to look for is Test_Basic ( Test/Basic folder )
With this, Magento will be able to find the file in the controllers folder with the class name Test_Basic_NameController where Name is the name of controller provided in the URL.
The <frontName> tag is used to distinguish our controller’s URL from others, hence it should be unique.
Refresh the cache from admin.
The methods of a controller can be executed with the following URL pattern:
http://<sitename>/frontName/ControllerName/ActionName
So, if our site is currently on localhost with the name magento, we can execute our controller’s method with the URL-
http://localhost/magento/custom/first/index
Since, index is considered as default, we can also call with the URL-
http://localhost/magento/custom/first
Loading the layout
If you want to load the current site’s layout, just add following two lines in your indexAction method-
$this->loadLayout() $this->renderLayout()
Call the url again and you should see the layout loaded for your action.