Answers:
在控制器类中使用以下代码来获取控制器,模块,操作和路由名称:
<?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();
}
}
在下面获取phtml
文件或controller
使用
echo $controllerName = $this->getRequest()->getControllerName();
echo $actionName = $this->getRequest()->getActionName();
echo $routeName = $this->getRequest()->getRouteName();
echo $moduleName = $this->getRequest()->getModuleName();
controller:index,action:index,route:cms,module:cms
希望对您有所帮助。
在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();
ObjectManager
直接实例化Direct。您应该通过DI注入所需的类/对象。
您也可以:
$this->_requestInterface->getFullActionName()
获取完整的动作名称