1

How could I give the controller's name (class name) and its method in routes.xml from a plugin ?

for insance, I have two front routes, and I would like them to point to :

in the file MyCompany/MyModule/Controller/MyPath/Index.php : method foo()

and

in the file MyCompany/MyModule/Controller/MyPath/Index.php : method bar()

Here is the routes.xml file

etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="foo_route" frontName="foo">
            <module name="MyCompany_MyModule" />
        </route>
        <route id="bar_superroute" frontName="bar">
            <module name="MyCompany_MyModule" />
        </route>
    </router>
</config>

Update :

I used Qaisar Satti's suggestion :

in index.php :

public function execute() {//InputInterface $input, OutputInterface $output) 
{
    $route = $this->getRequest()->getRouteName();
    $this->$route(); //this will call foo_route() or bar_superroute()
}


protected function foo_route() {
    $params = $this->request->getParams();
    //do some awesome things
}

protected function bar_superroute() {
    $params = $this->request->getParams();
    //do some other super awesome bar things
}
  • IF this is a bad approach to Routing/Controller, please, please, explain to me the proper way. I come from a MVC world, and routing are meant to link an URL to a controller+method . – Cedric Apr 11 '18 at 12:48
1

As far i know there is no direct method. You can get your route name by

$this->getRequest()->getRouteName();

Call your require method.

Or

You can do it via layout if you want too. Solution

1

Just an idea: Magento 2 comes from with Test Driven Development and SOLID principles. With the SOLID:

Single responsibility principle

a class should have only a single responsibility (i.e. changes to only one part of the software's specification should be able to affect the specification of the class).

So, I think this is the main reason why one controller class should have only action class.

One more thing, the controller class in Magento 2 is shorter and easier for management purpose in comparison with Magento 1.

  • This is a very good quote, and I should have seen it before using the other suggestion. – Cedric Apr 11 '18 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.