Magento 2 - How to Get Configuration Value Programmatically?

ยท

2 min read

๐Ÿ’ก
I wrote this article under Magento 2 version of 2.4.6, latest version might have difference approach.

There are several ways to retrieve system configuration, but there are 2 common approaches, they are using object manager and by injecting into construct method (__construct is the recommended one by Magento itself).

1. by Object Manager

.....
$scopeConfig = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Framework\App\Config\ScopeConfigInterface::class);

$configValue = $scopeConfig->getValue(
        'fiko/general/testing_config',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
    );
.....

Notes:

  • $scopeConfig = \Magento\Framewo....: we need to define what's the instance / class we want to import / use.

  • $configValue = $scopeCon....: time to retrieve the configuration, further notes will be on 2nd solution below

<?php

namespace Fiko\Training\Helper;

class Data
{
    public $scopeConfig;

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

Notes:

  • public $scopeConfig;: by the time PHP 8 released, it is mandatory to define the visibility (no dynamic property allowed). it can be public/protected/private, but in this case I would use public as it can be used by other instances.

  • ScopeConfigInterface $scopeConfig: interface we need to have in order to retrieve configuration.

public function getExampleConfig()
{
    $configValue = $this->scopeConfig->getValue(
        'fiko/general/testing_config',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
    );

    return $configValue;
}

Notes:

  • fiko/general/testing_config: it is the path of the configuration.

  • \Magento\Store\Model\ScopeInterface::SCOPE_STORE: It is the scope area (I assume you already know this).

    • I recommend to use SCOPE_STORE, as it will automatically retrieve the higher scope level (website or default) if it doesn't exist on store level.

References:

Did you find this article valuable?

Support Fiko Borizqy by becoming a sponsor. Any amount is appreciated!

ย