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.
<?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 !!
Leave a Comment