How can you fetch a system configuration value programmatically in Magento?

We always have a requirement to get value from `core_config_data` table in Magento 2. Magento uses ScopeConfigInterface to read config values from database located at /vendor/magento/framework/App/Config/ScopeConfigInterface.php. Do navigate this file to understand it better.

Method defined in the ScopeConfigInterface uses the Scope type as a parameter where ‘default’ is the default scope type. ScopeInterface located at /vendor/magento/module-store/Model/ScopeInterface.php have Scope Types available in the Magento as follows :

/**#@+
 * Scope types
 */
const SCOPE_STORES = 'stores';
const SCOPE_GROUPS   = 'groups';
const SCOPE_WEBSITES = 'websites';

const SCOPE_STORE   = 'store';
const SCOPE_GROUP   = 'group';
const SCOPE_WEBSITE = 'website';
/**#@-*/

Best example to check is the Magento own Model class.

/vendor/magento/module-cms/Model/GetUtilityPageIdentifiers.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Cms\Model;

use Magento\Cms\Api\GetUtilityPageIdentifiersInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

/**
 * Utility Cms Pages
 */
class GetUtilityPageIdentifiers implements GetUtilityPageIdentifiersInterface
{
    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * UtilityCmsPage constructor.
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Get List Page Identifiers
     * @return array
     */
    public function execute()
    {
        $homePageIdentifier = $this->scopeConfig->getValue(
            'web/default/cms_home_page',
            ScopeInterface::SCOPE_STORE
        );
        $noRouteIdentifier  = $this->scopeConfig->getValue(
            'web/default/cms_no_route',
            ScopeInterface::SCOPE_STORE
        );

        $noCookieIdentifier = $this->scopeConfig->getValue(
            'web/default/cms_no_cookies',
            ScopeInterface::SCOPE_STORE
        );

        return [$homePageIdentifier, $noRouteIdentifier, $noCookieIdentifier];
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *