Dotenv

The library for using .env files.

When to use Dotenv?

The .env should be used for sensitive information like passwords, hosts, keys, credentials, and all other values that can be changed depending on the environment, e.g., debug mode settings or logs level.


Installation

To install this package, run the standard command using Composer:

  • composer require quillstack/dotenv

The package will be ready to use after that.


Usage

You can use Quillstack Dotenv package when you want to use .env files in your project. If you created the .env file in the root directory of your project:

  • APP_DEBUG=true

You can load this .env file in your application:

  • $dotenv = new Dotenv('.env');
  • $dotenv->load();

Every time you need to know if your application works in debug mode, you can check it using this helper function:

  • if (env('APP_DEBUG')) {
  •     echo 'Debug mode';
  • }

You can also define a default value depending on the context:

  • if (env('APP_DEBUG', false)) {
  •     echo 'Debug mode';
  • }

Required keys

You can use another helper method for required keys. If required key is not found an exception will be thrown:

  • $dbHost = required('DATABASE_HOST');

The result if the key DATABASE_HOST is not set in the .env file:

  • DotenvValueNotSetException:
  • Value not set for key: DATABASE_HOST

Multi-line values

You can define multi-line values in your .env file by using \n separator instead of new lines for example:

  • PRIVATE_KEY="line1\nline2\nline3"