Accessing Configuration Values in Magento 2 and Adobe Commerce
Accessing Configuration Values in Magento 2 and Adobe Commerce
Configuration values control how your Magento 2 store behaves. You need to retrieve these configuration values programmatically to build flexible modules. This guide shows you how to access configuration values in Magento 2 and Adobe Commerce using the ScopeConfigInterface.
Table Of Content
What Are Configuration Values
Configuration values store all your admin panel settings. Magento stores these settings in the core_config_data database table. Each value has a path that follows the format section/group/field.
You can set configurations at different scopes:
- Default (applies to all stores)
- Website (applies to specific websites)
- Store View (applies to individual store views)
Tip
To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!
Create Your Configuration Structure
You define admin panel settings in a system.xml file. This file determines what appears in the admin configuration panel.
Here's a basic configuration setup:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="custom_module" translate="label" sortOrder="10">
<label>Custom Module</label>
</tab>
<section id="module_settings" translate="label" sortOrder="130"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>Module Settings</label>
<tab>custom_module</tab>
<resource>Vendor_Module::config</resource>
<group id="general" translate="label" sortOrder="10"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>General Settings</label>
<field id="enabled" translate="label" type="select"
sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable Module</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
</config>
This creates an "Enable Module" toggle in your admin panel at Stores > Configuration.
Build a Configuration Helper
Create a helper class that extends AbstractHelper or directly injects ScopeConfigInterface. The helper centralizes your configuration access.
Method 1: Using AbstractHelper
<?php
namespace Vendor\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;
class Config extends AbstractHelper
{
const XML_PATH_GENERAL = 'module_settings/general/';
public function __construct(Context $context)
{
parent::__construct($context);
}
private function getConfigValue($field, $storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_GENERAL . $field,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isEnabled($storeId = null)
{
return (bool) $this->getConfigValue('enabled', $storeId);
}
}
When you extend AbstractHelper, you get the scopeConfig property automatically without injecting it.
Method 2: Direct Injection (Recommended for Magento 2.4.5+)
Starting with Magento 2.4.5, inject ScopeConfigInterface directly instead of extending AbstractHelper:
<?php
namespace Vendor\Module\Helper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
const XML_PATH_GENERAL = 'module_settings/general/';
protected $scopeConfig;
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
public function getConfigValue($path, $storeId = null)
{
return $this->scopeConfig->getValue(
$path,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isEnabled($storeId = null)
{
return (bool) $this->getConfigValue(
self::XML_PATH_GENERAL . 'enabled',
$storeId
);
}
}
Understanding getValue Parameters
The getValue() method accepts three parameters:
- $path: Configuration path (section/group/field)
- $scope: Where to look for the value
- $storeId: Which store to check (optional)
Scope Configuration Options
You can retrieve values from different scopes:
| Scope Type | Constant | Use Case |
|---|---|---|
| Store View | ScopeInterface::SCOPE_STORE | Get value for specific store view |
| Website | ScopeInterface::SCOPE_WEBSITE | Get value for website level |
| Default | ScopeConfigInterface::SCOPE_TYPE_DEFAULT | Get global default value |
Example with different scopes:
// Get store-specific value
$storeValue = $this->scopeConfig->getValue(
'section/group/field',
ScopeInterface::SCOPE_STORE,
$storeId
);
// Get website-specific value
$websiteValue = $this->scopeConfig->getValue(
'section/group/field',
ScopeInterface::SCOPE_WEBSITE,
$websiteId
);
// Get default value
$defaultValue = $this->scopeConfig->getValue(
'section/group/field',
ScopeConfigInterface::SCOPE_TYPE_DEFAULT
);
Use Configuration in Controllers
Inject your helper into controllers to check configuration before executing logic:
<?php
namespace Vendor\Module\Controller\Adminhtml\Action;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Vendor\Module\Helper\Config;
class Execute extends Action
{
protected $config;
protected $processor;
public function __construct(
Context $context,
Config $config,
\Vendor\Module\Model\Processor $processor
) {
$this->config = $config;
$this->processor = $processor;
parent::__construct($context);
}
public function execute()
{
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
if (!$this->config->isEnabled()) {
$this->messageManager->addErrorMessage(
'Module is disabled in configuration'
);
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
try {
$this->processor->execute();
$this->messageManager->addSuccessMessage('Operation completed successfully');
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(
'Error: ' . $e->getMessage()
);
}
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
}
Additional Configuration Methods
Check Boolean Values
Use isSetFlag() for yes/no configurations:
public function isFeatureEnabled($storeId = null)
{
return $this->scopeConfig->isSetFlag(
'section/group/feature_enabled',
ScopeInterface::SCOPE_STORE,
$storeId
);
}
Get Multiple Values
Create methods for different configuration fields:
public function getApiKey($storeId = null)
{
return $this->getConfigValue('api_key', $storeId);
}
public function getApiEndpoint($storeId = null)
{
return $this->getConfigValue('api_endpoint', $storeId);
}
public function getTimeout($storeId = null)
{
return (int) $this->getConfigValue('timeout', $storeId);
}
Set Configuration Values Programmatically
Use command-line tools to set configuration values:
bin/magento config:set section/group/field "value"
bin/magento config:set --scope=store --scope-code=default section/group/field "value"
For programmatic updates, use the resource model:
<?php
use Magento\Config\Model\ResourceModel\Config as ConfigResource;
use Magento\Framework\App\Config\ScopeConfigInterface;
class ConfigUpdater
{
protected $configResource;
public function __construct(ConfigResource $configResource)
{
$this->configResource = $configResource;
}
public function updateConfig($path, $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0)
{
$this->configResource->saveConfig($path, $value, $scope, $scopeId);
}
}
Configuration Storage and Fallback
Magento merges all config.xml files into one XML tree, with later-loaded modules taking precedence. Values fall back from store view to website to default scope.
The fallback order:
- Store View (most specific)
- Website
- Default (least specific)
Best Practices
Keep your store updated and use secure settings for optimal performance. Follow these guidelines:
- Use Constants: Define configuration paths as constants
- Cache Helper: Helper methods automatically benefit from configuration caching
- Type Casting: Convert values to correct types (bool, int, string)
- Null Checks: Handle missing configuration gracefully
- Avoid ObjectManager: Always use dependency injection
Example with type safety:
public function getMaxItems($storeId = null): int
{
$value = $this->getConfigValue('max_items', $storeId);
return $value ? (int) $value : 10; // Default to 10
}
public function getAllowedTypes($storeId = null): array
{
$value = $this->getConfigValue('allowed_types', $storeId);
return $value ? explode(',', $value) : [];
}
Configuration in Templates
Access configuration in PHTML templates through helper:
<?php
$config = $this->helper('Vendor\Module\Helper\Config');
?>
<?php if ($config->isEnabled()): ?>
<div class="custom-feature">
<?= $this->escapeHtml($config->getTitle()) ?>
</div>
<?php endif; ?>
Debugging Configuration
Check current values using CLI:
# Show all configuration
bin/magento config:show
# Show specific path
bin/magento config:show section/group/field
# Show for specific scope
bin/magento config:show --scope=websites --scope-code=base section/group/field
Conclusion
Configuration management in Magento 2 requires understanding scope hierarchy and proper implementation. Create dedicated helper classes to access configuration values. Use dependency injection to inject ScopeConfigInterface or extend AbstractHelper for simpler implementations. Always specify the correct scope when retrieving values to ensure your store behaves correctly across different views and websites.
FAQs
What are configuration values in Magento 2?
Configuration values are settings stored in Magento 2 that control how the system behaves. They can be set globally, per website, or per store view, and include options like store information, payment methods, and custom module settings.
Where are Magento 2 configuration values stored?
Magento 2 stores configuration values in the core_config_data table in the database. Each entry has a path (section/group/field) and a scope (default, website, store) that determines its applicability.
How can I access configuration values programmatically?
You can access configuration values using dependency injection of the ScopeConfigInterface in your class. Example:
protected $scopeConfig;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
) {
$this->scopeConfig = $scopeConfig;
}
$value = $this->scopeConfig->getValue('section/group/field', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
How do I access configuration values from the CLI?
You can use the Magento CLI config:show command:
- Show all configuration:
bin/magento config:show - Show a specific path:
bin/magento config:show section/group/field - Show for a specific scope:
bin/magento config:show --scope=websites --scope-code=base section/group/field
What is the difference between default, website, and store scopes?
Configuration values in Magento 2 can have three scopes:
- Default: Applies to all websites and stores unless overridden.
- Website: Applies to all stores within a specific website.
- Store: Specific to a single store view, overriding website or default values.
Can I update configuration values programmatically?
Yes, you can update values using the ConfigWriterInterface:
protected $configWriter;
$this->configWriter->save('section/group/field', 'value', $scope, $scopeCode);
How do I check if a configuration value exists?
Use ScopeConfigInterface::isSetFlag() to check if a configuration value exists and is enabled:
$enabled = $this->scopeConfig->isSetFlag(
'section/group/field',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
Does clearing cache affect configuration values?
Yes. After changing configuration values, either via admin, CLI, or programmatically, you should clear the cache with bin/magento cache:flush to ensure the new values take effect.
How do configuration values work with custom modules?
Custom modules can define their own configuration values in system.xml. These values can then be accessed using the same ScopeConfigInterface methods, respecting the scope hierarchy.
What are best practices for working with configuration values?
Always use dependency injection to access values, respect scope hierarchy, clear caches after updates, and avoid hardcoding values. For custom modules, document paths clearly and provide default values in config.xml.




