Magento2:检查它是前端还是后端?


Answers:


22

阅读更多:blog.mageprince.com

使用objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); //frontend or adminhtml or webapi_rest

有依赖注入

protected $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function getArea()
{
    return $this->_state->getAreaCode();
}

注意:根据magento2编码标准,请勿直接在文件中使用对象管理器实例


1
1为依赖注入
PЯINCƏ

+1 @PЯINCƏ根据Magento编码标准,请勿在构造方法中使用完整的类名。使用use语句声明完整的类,并仅将类名声明为Construct()方法。
Rakesh Jesadiya

1
@RakeshJesadiya林不同意你的意见,请参阅这个问题:magento.stackexchange.com/questions/106096/...
PЯINCƏ

6

人们已经回答了这个问题。我只是在做的更好。

const AREA_CODE = \Magento\Framework\App\Area::AREA_ADMINHTML;

private $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function isAdmin()
{
    $areaCode = $this->_state->getAreaCode();
    return $areaCode == self::AREA_CODE;
}

嗨@dinesh,我们可以只为管理员启用维护模式吗?
Jafar Pinjar

不,该选项不可用。
Dinesh Yadav

3

使用以下代码

$objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectmanager->get('Magento\Framework\App\State');
if($state->getAreaCode() == 'frontend')
  //frontend
else
  //backend

2

尝试下面的代码检查您是否在管理员区域

function df_is_admin($store = null) {
    /** @var \Magento\Framework\ObjectManagerInterface $om */
    $om = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Framework\App\State $state */
    $state =  $om->get('Magento\Framework\App\State');
    return 'adminhtml' === $state->getAreaCode();
}

0
 public function isAdmin(){
      return ('adminhtml' == $this->_state->getAreaCode());
 }
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.