Magento 2:如何获取控制器,模块,操作和路由器名称?


Answers:


33

在控制器类中使用以下代码来获取控制器,模块,操作和路由名称:

<?php
    namespace Custom\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $request;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Request\Http $request
    ){
        parent::__construct($context);
        $this->request = $request;
    }

    public function execute()
    {
        $moduleName = $this->request->getModuleName();
        $controller = $this->request->getControllerName();
        $action     = $this->request->getActionName();
        $route      = $this->request->getRouteName();

        echo $moduleName."<br/>";
        echo $controller."<br/>";
        echo $action."<br/>";
        echo $route."<br/>";

        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}

@Manashvi,您好,我们可以从ReferralUrl获取控制器和动作名称吗?
jafar pinjar

14

在下面获取phtml文件或controller使用

echo $controllerName = $this->getRequest()->getControllerName();
echo $actionName = $this->getRequest()->getActionName();
echo $routeName = $this->getRequest()->getRouteName();
echo $moduleName = $this->getRequest()->getModuleName(); 

如何获得主页控制器操作来设置观察者?
supriya mishra

如果您测试此代码,它将在首页输出, controller:index,action:index,route:cms,module:cms希望对您有所帮助。
Qaisar Satti

@QaisarSatti,我们可以从引荐网址中获取控制器和动作名称吗?$ this-> redirect-> getRefererUrl();
贾法尔·品哈尔(Jafar Pinjar)

5

在magento 2中使用以下代码段来phtml,controller和event

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$requestInterface = $objectManager->get('Magento\Framework\App\RequestInterface');

$routeName      = $requestInterface->getRouteName();
$moduleName     = $requestInterface->getModuleName(); 
$controllerName = $requestInterface->getControllerName(); 
$actionName     = $requestInterface->getActionName();

3
您不应该ObjectManager直接实例化Direct。您应该通过DI注入所需的类/对象。
7ochem '16


1

您可以从请求对象获取这些信息。

在您的controller课程中:

$routeName        = $this->getRequest()->getRouteName();
$moduleName       = $this->getRequest()->getModuleName();
$controllerName   = $this->getRequest()->getControllerName();
$actionName       = $this->getRequest()->getActionName();

我希望这将有所帮助。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.