Hello Devs, In today’s blog, we are going to see how we can get value from env.php in Magento 2.
As Magento 2 developers, we all are familiar with the env.php file, and it has to have an important role in Magento as it is the place where Magento 2 stores the database credentials, backend URL, enabled cache types, etc. The app/etc/env.php file is autogenerated. It stores a piece of information which is unique to your Magento 2 installation.
Ever wondered, how we can access those values in our code programmatically?
During development in some cases, you will need to access those values in your custom code. You can easily retrieve values from this file using the use of \Magento\Framework\App\DeploymentConfig class.
Let’s see a quick example demonstrating how to access a “database name” of your Magento installation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); namespace VendorName\ModuleName\Helper; class Data { private const DB_NAME_PATH = 'db/connection/default/dbname'; /** * @var \Magento\Framework\App\DeploymentConfig */ protected $deploymentConfig; /** * @param \Magento\Framework\App\DeploymentConfig $deploymentConfig */ public function __construct( \Magento\Framework\App\DeploymentConfig $deploymentConfig ) { $this->deploymentConfig = $deploymentConfig; } public function getDatabaseName() { $databaseName = $this->deploymentConfig->get(self::DB_NAME_PATH); return $databaseName; } } |
In the above example when you call this function it will return the database name.
You can change this code as per your requirement.
You may also like :
How to create a root script in Magento 2?
How to configure Magento 2 coding standards in visual studio code?
Get Serialize value in array format using Magento 2
That’s it for this tutorial, See you in the next blog. Thank You !!