Magento 2控制器中如何正确获取模块的setup_version参数
报错原因
- 核心原因是你重写了控制器的构造方法后,没有调用父类
AbstractIndex的构造方法,导致父类初始化必须的Context依赖没有传入,父类内部属性为空,所以执行到父类的get()方法时抛出空对象调用错误。 - 额外问题:你使用
ScopeConfigInterface读取modules/My_Module/setup_version的逻辑本身是错误的,setup_version不存在于系统配置项中,该方法无法读取到对应值。
正确获取模块setup_version的方案
你需要使用Magento\Framework\Module\ModuleListInterface来读取模块的配置信息,同时修正构造方法调用父类构造逻辑,完整代码如下:
<?php namespace My\Module\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\Module\ModuleListInterface; class Version extends AbstractIndex { /** * @var ModuleListInterface */ protected $moduleList; public function __construct( Context $context, ModuleListInterface $moduleList ) { parent::__construct($context); $this->moduleList = $moduleList; } public function execute() { $moduleInfo = $this->moduleList->getOne('My_Module'); $version = $moduleInfo['setup_version'] ?? '未定义版本'; // 规范实现建议返回响应对象而非直接echo,示例如下 $result = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_RAW); return $result->setContents($version); } }
修改完成后执行以下命令清理依赖缓存即可生效:bin/magento setup:di:compile
如果是开发模式下也可以直接删除generated目录,清理缓存:bin/magento cache:flush
内容的提问来源于stack exchange,提问作者Alexandru R
相关产品推荐
相关产品推荐

