Magento 2中Mage::getModel('adminhtml/config_data')的等价实现方式
Magento 1.9 到 Magento 2 的配置保存代码等价实现
嘿,我来帮你把这段Magento 1.9的配置保存代码转换成Magento 2的版本~
首先先回顾下你这段M1代码的作用:它是用来保存全局范围(website和store都设为null)的配置项,对应后台的「全局」配置标签页。
在Magento 2中,我们不再像M1那样直接调用静态Mage::getModel()方法,而是通过依赖注入来获取对应的配置资源类,下面是具体的实现步骤:
1. 依赖注入配置资源类
首先在你的类的构造函数中注入Magento\Config\Model\ResourceModel\Config类,这是M2中负责保存配置的核心类:
protected $configResource; public function __construct( \Magento\Config\Model\ResourceModel\Config $configResource ) { $this->configResource = $configResource; }
2. 等价的配置保存代码
M2的saveConfig方法需要传入完整的配置路径(格式为section/group/field),而不是M1中分开的$section和$groups参数。对应你原来的全局配置逻辑,代码如下:
// 替换成你的完整配置路径,比如 'general/store_information/name' $configPath = $section . '/' . $group . '/' . $field; // 替换成你要设置的配置值 $configValue = 'Your Config Value'; $this->configResource->saveConfig( $configPath, $configValue, 'default', // 对应M1中website和store为null的全局范围 0 // 全局范围的scopeId固定为0 );
如果需要保存多个配置项
如果原来的M1代码中$groups是包含多个字段的数组,你需要循环处理每个字段,因为M2的saveConfig是针对单个配置项的:
// 示例:键为完整配置路径,值为对应配置值的数组 $configItems = [ 'general/store_information/name' => 'My Awesome Store', 'general/store_information/phone' => '123-456-7890', 'catalog/frontend/list_mode' => 'grid-list' ]; foreach ($configItems as $path => $value) { $this->configResource->saveConfig( $path, $value, 'default', 0 ); }
3. 可选:清理配置缓存
Magento 2会缓存配置项,所以保存后建议清理相关缓存,确保配置立即生效。你可以注入缓存相关类来实现:
// 先在构造函数中注入缓存类 protected $cacheTypeList; protected $cacheFrontendPool; public function __construct( \Magento\Config\Model\ResourceModel\Config $configResource, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool ) { $this->configResource = $configResource; $this->cacheTypeList = $cacheTypeList; $this->cacheFrontendPool = $cacheFrontendPool; } // 保存配置后执行缓存清理 $cacheTypes = ['config', 'full_page']; foreach ($cacheTypes as $type) { $this->cacheTypeList->cleanType($type); } foreach ($this->cacheFrontendPool as $cacheFrontend) { $cacheFrontend->getBackend()->clean(); }
补充说明
- 如果需要保存到特定的website或store,只需要修改
saveConfig的后两个参数:- 保存到website:第三个参数传
'websites',第四个参数传对应website的ID - 保存到store:第三个参数传
'stores',第四个参数传对应store的ID
- 保存到website:第三个参数传
内容的提问来源于stack exchange,提问作者Sohil Jain
相关产品推荐
相关产品推荐

