Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento 2:检查模块是否已安装,启用或处于活动状态

本文介绍了如何检查Magento 2中是否已安装/启用或激活模块。

依赖注入和对象管理器方式都显示如下。

使用依赖注入(DI)

以下是我的自定义模块(Chapagain_HelloWorld)的块类。我在模块的块类的构造函数中注入了\ Magento \ Framework \ Module \ Manager类的对象。

app / code / Chapagain / HelloWorld / Block / HelloWorld.php

<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_moduleManager;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    )
    {    
        $this->_moduleManager = $moduleManager;
        parent::__construct($context, $data);
    }
    
    /**
     * Whether a module is enabled in the configuration or not
     *
     * @param string $moduleName Fully-qualified module name
     * @return boolean
     */
    public function isModuleEnabled($moduleName)
    {
        return $this->_moduleManager->isEnabled($moduleName);
    }
    
    /**
     * Whether a module output is permitted by the configuration or not
     *
     * @param string $moduleName Fully-qualified module name
     * @return boolean
     */
    public function isOutputEnabled($moduleName)
    {
        return $this->_moduleManager->isOutputEnabled($moduleName);
    }
}
?>

现在,我们在模板(.phtml)文件中使用这些功能。

var_dump($block->isModuleEnabled('YourNamespace_YourModule'));
var_dump($block->isOutputEnabled('YourNamespace_YourModule'));
 
var_dump($block->isModuleEnabled('Magento_Catalog'));
var_dump($block->isOutputEnabled('Magento_Catalog'));

使用对象管理器

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$moduleManager = $objectManager->get('\Magento\Framework\Module\Manager');
 
var_dump($moduleManager->isEnabled('YourNamespace_YourModule'));
var_dump($moduleManager->isOutputEnabled('YourNamespace_YourModule'));
 
var_dump($moduleManager->isEnabled('Magento_Catalog'));
var_dump($moduleManager->isOutputEnabled('Magento_Catalog'));

希望这可以帮助。谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论