FastSitePHP\Environment\DotEnv

Loads environment variables from a [.env] file into [getenv()] and [$_ENV].

This class is a port of the widely used node [dotenv] package so the following syntax is supported:

  - Empty lines are skipped
  - Lines beginning with # are treated as comments
  - Empty values become empty strings ([EMPTY=] becomes {EMPTY: ''})
  - Whitespace is trimmed for unquoted values ([FOO= some value ] becomes {FOO: 'some value'})
  - Single and double quoted values are escaped ([SINGLE_QUOTE='quoted'] becomes {SINGLE_QUOTE: "quoted"})
  - Double quoted values expand new lines (example: [MULTILINE="new\nline"])

This class is minimal like the node pacakage and does not support nested variables, inline shell execution, or advanced validation. If you prefer to use those features then PHP packages [vlucas/phpdotenv] or [symfony/dotenv] are recommended.

Because FastSitePHP's DotEnv Class is minimal and has fast performance it can be used for production sites, however it’s a good idea to load it from middleware or controller logic on needed routes rather than loading it for every route.

Código Fonte

GitHub

Código de Exemplo

Utilize um arquivo [.env]

// Carrega variáveis de ambiente de um arquivo [.env] para dentro de
// [getenv()] e [$_ENV]. O FastSitePHP DotEnv é um porte do pacote Node
// [dotenv] então a mesma sintaxe utilizada por projetos Node é suportada.
$vars = \FastSitePHP\Environment\DotEnv::load($dir);

// Utilize variáveis de um arquivo depois de lê-lo. Variáveis são somente
// definidas de um arquivo se elas ainda não existirem.
$value = getenv('DB_CONNECTION');
$value = $_ENV['DB_CONNECTION'];

// Carregue um arquivo utilizando o formato [.env]. O caminho completo do
// arquivo é especificado de forma que possa receber qualquer nome.
$vars = \FastSitePHP\Environment\DotEnv::loadFile($file_path);

// Opcionalmente, exija que hajam chaves no arquivo.
$required_vars = ['DB_ORACLE', 'DB_SQL_SERVER'];
$vars = \FastSitePHP\Environment\DotEnv::load($dir, $required_vars);

Métodos

load($dir_path, array $required_vars = array())

Função Estática

Load a [.env] file from a directory. The directory and file must exist or an exception will be thrown.

An optional array [$required_vars] can be passed and if any key from the array do not exist in the file an exception will be thrown. The actual values are not validated by this class.

Returns an array of all variables read from the file.

Retorna: array

loadFile($file_path, array $required_vars = array())

Função Estática

Load a file using [.env] file format. The full path of the file is specified so it can be named anything.

Retorna: array