follow me

Set Store Configuration Programatically in Magento 2

Something I found useful one day was the ability to easily set the store configuration for a module’s settings programmatically.

namespace JerryLopez\Example\Scope;

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

/**
 * Module configuration settings
 */
class Config
{
    const CONFIG_PATH_ENABLED = 'example/general/enabled';

    public function __construct(
        private readonly WriterInterface $writer
    ) {
    }

    public function setEnabled(
        $value, 
        $scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
        $scopeCode = null
    ) {
        $this->writer->save(self::CONFIG_PATH_ENABLED, $value, $scopeType, $scopeCode);
        return $this;
    }
}