wpscholar/phpdotenv

从.env文件中加载环境变量。

1.0.1 2019-09-13 16:55 UTC

This package is auto-updated.

Last update: 2024-09-14 03:41:26 UTC


README

一个用于PHP的.env文件解析和加载库。

自动将变量加载到多个上下文中

  • getenv() (默认)
  • $_ENV (默认)
  • $_SERVER (默认)
  • apache_getenv (可选)
  • PHP常量 (可选)
  • 全局变量 (可选)
  • 自定义配置数组 (可选)

为什么?

您永远不应该将敏感凭证存储在代码中。配置存储在环境中十二要素应用的十项原则之一。任何可能在部署环境之间发生变化的东西 - 例如数据库凭证或第三方服务的凭证 - 都应该从代码中提取出来,存储到环境变量中。

要求

  • PHP 5.4

安装

使用Composer,运行composer require wpscholar/phpdotenv

确保您的代码中有处理自动加载的行

<?php

require __DIR__ . '/vendor/autoload.php';

用法

创建一个新的加载器,并使用任何可用的方法来帮助自定义配置

<?php

$loader = new wpscholar\phpdotenv\Loader(); // Can also do wpscholar\phpdotenv\Loader::create() 
$loader
    ->config([ // Must be used to customize adapters, can also be used to set defaults or required variables.
        'adapters' => [
            'apache',   // Uses apache_setenv() 
            'array',    // Uses a custom array
            'define',   // Uses define() to set PHP constants
            'env',      // Uses $_ENV
            'global',   // Sets global variables
            'putenv',   // Uses putenv()
            'server'    // Uses $_SERVER
        ], 
        'defaults' => [
            'foo' => 'bar' // Set a default value if not provided in .env  	
        ],
        'required' => [
            'bar', // Require that a variable be defined in the .env file. Throws an exception if not defined.
            'baz',
        ],
    ])
    ->required([ // Another way to define required variables
        'bar',
        'baz',
        'quux',    	
    ])
    ->setDefaults([ // Another way to set defaults
        'foo' => 'bar',	
    ])
    ->parse([ __DIR__ . '/.env', dirname( __DIR__ ) . '/.env' ]) // Array of file paths to check for a .env file. Parses found file and loads vars into memory.
    ->set( 'qux', $loader->get('foo') ); // Override variables after loading, but with access to existing variables before they are loaded into the environment.
    
// Validate variable values after parsing the .env file, but before loading the results into the environment.
$loader->validate('foo')->notEmpty();
$loader->validate('bar')->isBoolean();
$loader->validate('baz')->isInteger();
$loader->validate('qux')->notEmpty()->allowedValues( [ 'bar', 'baz' ] ); // Validations can be chained together.
$loader->validate('quux')->assert(function( $value ) { // Apply your own custom validation assertions.
    return is_int($value) && $value > 0 && $value <= 10;	
});

// Call load() to load variables into the environment without overwriting existing variables.
$loader->load();

// Call overload() to load variables into the environment, overwriting any existing variables.
$loader->overload();

可以创建多个加载器实例,每个实例加载不同的.env文件,并将变量加载到不同的上下文中。

自定义配置数组示例用法

<?php

$loader = wpscholar\phpdotenv\Loader::create();
$loader
    ->config([ 'adapters' => 'array'] ) // All values are self-contained in an array within the loader.
    ->required([ 'bar', 'baz', 'quux', ])
    ->setDefaults([ 'foo' => 'bar' ])
    ->parse( __DIR__ . '/.env' )
    ->set( 'qux', $loader->get('foo') )
    ->load();

$config = $loader->all(); // Get an array containing the final values.

$bar = $loader->get('bar'); // Get a single value.

WordPress wp-config.php 示例用法

<?php

require __DIR__ . '/vendor/autoload.php';

use wpscholar\phpdotenv\Loader;

$loader = new Loader();
$loader
	->config( [ 'adapters' => 'define' ] ) // Will only set PHP constants
	->required( [ // Requires these be set in the .env file
		'DB_NAME',
		'DB_USER',
		'DB_PASSWORD',
	] )
	->setDefaults( [ // Defaults to use if not defined in .env file
		'ABSPATH'         => __DIR__ . '/wp',
		'DB_CHARSET'      => 'utf8',
		'DB_COLLATE'      => '',
		'DB_HOST'         => 'localhost',
		'WP_DEBUG'        => false,
		'WP_TABLE_PREFIX' => 'wp_',
	] )
	->parse( __DIR__ . '/.env' ) // Parse the .env file
	->set( 'WP_HOME', 'https://' . $_SERVER['HTTP_HOST'] )
	->set( 'WP_SITEURL', $loader->get( 'WP_HOME' ) . '/wp' ) // Use previously defined values to set other values.
	->set( 'WP_CONTENT_DIR', __DIR__ . '/content' )
	->set( 'WP_CONTENT_URL', $loader->get( 'WP_HOME' ) . '/content' )
	->set( 'DISALLOW_FILE_EDIT', true )
	->load(); // We could use overload() here, but we can't overwrite constants in PHP either way.

$table_prefix = WP_TABLE_PREFIX;

require_once( ABSPATH . 'wp-settings.php' );

创建一个.env文件

wp-config.php示例的.env文件样本

DB_NAME=local
DB_USER=root
DB_PASSWORD=root
WP_DEBUG=true
SCRIPT_DEBUG=true

探索所有.env文件解析器的功能。

遵循的规则

在使用phpdotenv时,您应努力遵循以下规则

  • 将您的.env文件添加到.gitignore文件中,以防止敏感数据提交到项目仓库。
  • 使用.env.example为项目设置默认配置。这允许您的开发团队以适用于他们本地环境的方法覆盖默认设置。
  • 尽可能设置合理的默认值。
  • 在必要时,为凭证添加注释,提供关于它们是什么、如何使用以及如何获取新凭证的信息。
  • 由于phpdotenv在定义环境变量时使用更宽松的程序,请确保您的.env文件与您的shell兼容。一种测试的好方法是运行以下命令
# Source in your .env file
source .env
# Check an environmental variable
foo
  • 尽可能避免在生产设置中运行phpdotenv。相反,在应用程序加载之前,在您的web服务器、进程管理器或bash中设置环境变量。