如何使用Magento 2以编程方式在core_config_data中设置值?


13

我知道您可以使用以下命令在Magento 1中设置配置数据:

Mage::getModel('core/config')->saveConfig('my/path/whatever', $value);

您可以使用以下命令在Magento 2中获取配置数据:

protected $_scopeConfig

public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig) {
    $this->_scopeConfig = $scopeConfig;
}

+

$this->_scopeConfig->getValue( 'path/of/config', \Magento\Store\Model\ScopeInterface::SCOPE_STORE );

但我不知道如何在Magento 2中保存配置数据

Answers:


24

这是您应该如何将数据保存在magento2 core_config_data中的方法

    use Magento\Framework\App\Config\ScopeConfigInterface;

    /**
     *  @var \Magento\Framework\App\Config\Storage\WriterInterface
     */
    protected $configWriter;

    /**
     *
     * @param \Magento\Framework\App\Config\Storage\WriterInterface $configWriter
     */
    public function __construct(
        ....
        \Magento\Framework\App\Config\Storage\WriterInterface $configWriter
        .....
    )
    {
        $this->configWriter = $configWriter;
    }

在您的调用方法中添加以下行:

$this->configWriter->save('my/path/whatever',  $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0);

6

您可以注入ConfigInterface类并使用它保存值。

protected $_configInterface;

public function __construct(
    \Magento\Framework\App\Config\ConfigResource\ConfigInterface $configInterface
) {
    $this->_configInterface = $configInterface;
}

然后您可以在您的方法中使用它,例如

$this->_configInterface
    ->saveConfig('section/group/field', $value, 'default', 0);

1
请勿这样做,除非您确定不需要修剪路径。建议使用configWriter
Chuvisco 18'Apr
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.