Magento 2 is a flexible ECommerce platform that provides you with various options to customize your store to your needs. Thus, as a developer, you have to be aware of the coding matters to make everything works as flawlessly as possible.
There may be dozens of tasks that have to be solved programmatically, for instance, getting current URL or getting product by ID. However, it always goes down to configuration. So, it might also be useful to know how to get config value in Magento 2. And this is exactly what you'll learn today.
There are two ways to get config value in Magento 2. Let's have a look at both in more detail.
Post Contents [hide]
Get Config Value Using Dependency Injection
One of the most common methods to get configuration value in Magento is dependency injection.
In order to apply it, you need to go to the phtml block file and create a _construct function:
<?php
namespace Vendor\ModuleName;
class ClassName
{
public $scopeConfig;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
) {
$this->scopeConfig = $scopeConfig;
}
public function getConfigValue($sku)
{
return $this->scopeConfig->getValue(
'section/group/field',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
);
}
}
Get Config Value Using the Object Manager
There is one more way to get config value in Magento 2. You can also use the Object Manager.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');
$scopeConfig = $objectManager->create(\Magento\Framework\App\Config\ScopeConfigInterface::class);
$valueFromConfig = $scopeConfig->getValue(
'mfblog/general/enabled',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
);
Note: we don't recommend using the object manager directly. Even though it's quite easy to apply, it hides the real dependencies of the class.
So here you have two possible ways to get the config value in Magento 2. Just choose the one you feel more comfortable working with.
But of course, you don't have to stop here. You might as well learn how to get order data by increment ID to be more prepared for different development cases.