Skip to content

Create Magento 2 Module (Controller) Part II

here step how to working with controller, i will create 2 controllers file, my objective is, to run following url

http://127.0.0.1/magento21/index.php/hellomagentoworld/index/index   and
http://127.0.0.1/magento21/index.php/hellomagentoworld/index/test

  1. create file app\code\Ansyori\HelloWorld\etc\frontend\routes.xml
  2. <?xml version="1.0"?>
     
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
        <router id="standard">
            <route id="hellomagentoworld" frontName="hellomagentoworld">
                <module name="Ansyori_HelloWorld" />
            </route>
        </router>
    </config>
  3. next, create file app\code\Ansyori\HelloWorld\Controller\Index\Index.php
  4. <?php
    namespace Ansyori\HelloWorld\Controller\Index;
     
    class Index extends \Magento\Framework\App\Action\Action
    {
        public function execute()
        {
            echo 'Hello World!';
        }
    }
  5. and app\code\Ansyori\HelloWorld\Controller\Index\Test.php
  6. <?php
    namespace Ansyori\HelloWorld\Controller\Index;
     
    class Test extends \Magento\Framework\App\Action\Action
    {
        public function execute()
        {
            echo 'Test Horray!';
        }
    }
    
  7. dont forget, clear magento cache!
  8. then try open both URLs on your browser :
  9. http://127.0.0.1/magento21/index.php/hellomagentoworld/index/index
    http://127.0.0.1/magento21/index.php/hellomagentoworld/index/test

 

Comments are closed.