Magento 2: Programmatically Add a Value to `core_config_data`

There is the same saveConfig method: https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Config/Model/ResourceModel/Config.php#L26-L61

A usage example from the core: https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Payment/Observer/UpdateOrderStatusForPaymentMethodsObserver.php#L59-L64


I wouldn't use a model or a resource model, but \Magento\Framework\App\Config\Storage\WriterInterface or \Magento\Framework\App\Config\ConfigResource\ConfigInterface (the first delegating to the second).

Pretty straight-forward, too:

use Magento\Framework\App\Config\Storage\WriterInterface;

class SomeClass {

    public function __construct(WriterInterface $configWriter)
    {
        $configWriter->save('some/config/path', 'some value');
    }
}

You can also use \Magento\Config\Model\Config::save. Below a simple sample:

$configData = [
    'section' => 'MY_SECTION',
    'website' => null,
    'store'   => null,
    'groups'  => [
        'MY_GROUP' => [
            'fields' => [
                'MY_FIELD' => [
                    'value' => $myValue,
                ],
            ],
        ],
    ],
];

// $this->configFactory --> \Magento\Config\Model\Config\Factory
/** @var \Magento\Config\Model\Config $configModel */
$configModel = $this->configFactory->create(['data' => $configData]);
$configModel->save();

This syntax is not "simple", but it's more safe for some case. Du to the save logic, the action might be slower than direct access to the db.

In my case, $value need to be encrypted. In system.xml, I set the backend model for the field, and the save logic encrypt the data.

Edit: \Magento\Config\Model\Config::setDataByPath more simple to use