Magento 2: Read deploymentConfig

Magento 2: Read deploymentConfig

In Magento2 it is sometimes necessary to have several configuration entries which you want to set differently in your staging or development environment than in LIVE.

You can solve the whole thing via the file app/etc/env.php.

Fill in your Config here first of all, what you need.
I’ve listed what this might look like.

In the example below we have the category my_config_category and a property config_key, which contains the value config_value.

return [
    'my_config_category' => [
        'config_key' => 'config_value'
    // other default configs
    // ...


After we have defined our properties in the upper file, we now take care of reading out the properties.
We replay the whole thing once in a helper.

It is important that you get the DeploymentConfig in the constructor and save it in a variable, in our case $deploymentConfig.
Please remember that you can only do this by using Dependency Injection.
If you don’t know what this is, you can read about it here:

In the function getMyConfigValue we will now read the Config.
By calling the get-function of the config-object you can now read the value from your env.php by passing the category and property as string (i.e. my_config_category/config_key).


use Magento\Framework\App\DeploymentConfig;

class Data extends AbstractHelper {

    /** @var DeploymentConfig */
    private $deploymentConfig;
    public function __construct(DeploymentConfig $deploymentConfig) {
        $this->deploymentConfig = $deploymentConfig;

    public function getMyConfigValue() {
        // will return the string "config_value" from the app/etc/env.php
        return $this->deploymentConfig->get("my_config_category/config_key");

That’s about it.
Please remember that you never load objects like the Config directly via the ObjectManager:

It’s possible to do this, but everyone advises against it, because it’s not what Magento2 is designed for.
You have to compile the scripts after such a change, which took me 15 minutes according to the development environment, yes. But in this case you should really pay attention to clean code.

Since Magento does not want this way with the ObjectManager itself, it is also quite possible that Magento will lock this itself sooner or later. So in this case it is better to stay clean.

If you have any questions about this topic or the Dependency Injection, feel free to ask me.

Leave a comment