code-distortion/fluent-dotenv 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

code-distortion/fluent-dotenv

Composer 安装命令:

composer require code-distortion/fluent-dotenv

包简介

A wrapper with a fluent interface for new and old versions of vlucas/phpdotenv or symfony/dotenv, providing a common interface to easily read values from .env files

README 文档

README

Latest Version on Packagist PHP Version vlucas/phpdotenv symfony/dotenv GitHub Workflow Status Buy The World a Tree Contributor Covenant

code-distortion/fluent-dotenv is a wrapper with a fluent interface for new and old versions of vlucas/phpdotenv and symfony/dotenv, providing a common interface to easily read values from .env files.

Table of Contents

Introduction

.env files are an important tool as they allow for customisation of projects between environments.

The motivation behind this package is to provide a way to interact with the different versions of vlucas/phpdotenv or symfony/dotenv with a single interface.

This has been helpful for me when building packages that need to support a wide range of other packages.

First released in 2013, vlucas/phpdotenv by Vance Lucas and Graham Campbell is the most used PHP solution for loading values from .env files. Please have a look at their page for a more detailed description of what .env files are and why they're used.

symfony/dotenv was first released in 2017 as an alternative that's a part of Symfony framework family.

Overview

This package provides a new fluent interface for vlucas/phpdotenv and symfony/dotenv, and adds new features, including the ability to:

  • Perform validation - make sure values are not empty, are integers, booleans, are limited to a specific set of values, match a regex or validate via a callback,
  • Specify values to explicitly pick or ignore,
  • Specify values that are required,
  • Type casting to boolean or integer,
  • Populate $_ENV and $_SERVER values if you like, choosing whether to override values that already exist or not.

Installation

Install the package via composer:

composer require code-distortion/fluent-dotenv

You must also include either vlucas/phpdotenv or symfony/dotenv in your project:

composer require vlucas/phpdotenv
# or
composer require symfony/dotenv

FluentDotEnv will automatically detect which of these dotenv packages are installed and use it. You can also choose explicitly if you like.

Usage

Reading values from .env files

use CodeDistortion\FluentDotEnv\FluentDotEnv;

// simply load the values from one or more .env files
$fDotEnv = FluentDotEnv::new()->load('path/to/.env');
$fDotEnv = FluentDotEnv::new()->load(['path/to/.env', 'path/to/another.env']);

// don't throw an exception if the file doesn't exist
$fDotEnv = FluentDotEnv::new()->safeLoad('path/to/missing.env');

// get all the loaded values as an associative array
$allValues = $fDotEnv->all();

// get a single value
$host = $fDotEnv->get('HOST');

// get several values (returned as an associative array)
$dbCredentials = $fDotEnv->get(['HOST', 'PORT', 'USERNAME', 'PASSWORD']);

NOTE: Over time, vlucas/phpdotenv and symfony/dotenv have improved the way they interpret values from .env files (e.g. multi-line variables). The underlying version of these package/s you use will determine how the .env values are interpreted.

Filtering

If you only want to load specific keys, you can specify them. Other values from your .env file will be ignored:

$fDotEnv = FluentDotEnv::new()
    ->pick('MY_KEY1')              // add a key to pick
    ->pick('MY_KEY2')              // values can be passed individually
    ->pick(['MY_KEY3', 'MY_KEY4']) // or multiple as an array
    ->load('path/to/.env');

Conversely, particular keys can be ignored:

$fDotEnv = FluentDotEnv::new()
    ->ignore('MY_KEY1')              // add a key to ignore
    ->ignore('MY_KEY2')              // values can be passed individually
    ->ignore(['MY_KEY3', 'MY_KEY4']) // or multiple as an array
    ->load('path/to/.env');

Validation

Validation can be applied to the values in an .env file. A CodeDistortion\FluentDotEnv\Exceptions\ValidationException exception will be thrown when a value fails validation:

$fDotEnv = FluentDotEnv::new()

    // make sure these keys exist
    ->required('MY_KEY')
    ->required(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they aren't empty
    ->notEmpty('MY_KEY')
    ->notEmpty(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they are integer strings
    ->integer('MY_KEY')
    ->integer(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they are boolean strings
    // i.e. "true", "false", "On", "Off", "Yes", "No", "1" and "0"
    ->boolean('MY_KEY')
    ->boolean(['MY_KEY1', 'MY_KEY2'])

    // when a key exists, make sure its value is in a predefined list
    ->allowedValues('MY_KEY', ['value-1', 'value-2'])
    // allow predefined values for a multiple keys
    ->allowedValues(['MY_KEY1', 'MY_KEY2'], ['value-1', 'value-2'])
    // different predefined values can be specified for different keys in one go
    ->allowedValues([
        'MY_KEY1' => ['value-1', 'value-2'],
        'MY_KEY2' => ['value-a', 'value-b'],
    ])

    // when a key exists, make sure its value matches a regular expression
    ->regex('MY_KEY', '/^[0-9]+\.[0-9]{2}$/')
    // the same regex can be applied to multiple keys
    ->regex(['MY_KEY1', 'MY_KEY2'], '/^[0-9]+\.[0-9]{2}$/')
    // different regexes can be applied to different keys in one go
    ->regex([
        'MY_KEY1' => '/^[0-9]+\.[0-9]{2}$/',
        'MY_KEY2' => '/^[a-z]+$/'
    ])

    // when a key exists, validate it's value via a callback
    ->callback('MY_KEY', $callback)
    // the same callback can be applied to multiple keys
    ->callback(['MY_KEY1', 'MY_KEY2'], $callback)
    // different callbacks can be applied to different keys in one go
    ->callback([
        'MY_KEY1' => $callback1,
        'MY_KEY2' => $callback2,
    ])
    // validate *all* values via a callback
    ->callback(function (string $key, $value) {
        return true; // or false
    })

    // the validation is applied when load is called
    ->load('path/to/.env');

Casting values

Values retrieved using get(…) or all(…) are returned as strings.

castBoolean(…) and castInteger(…) are available for convenience to retrieve values as booleans or integers (null will be returned when the values aren't "booleans" or integers).

$fDotEnv = FluentDotEnv::new()->load('path/to/.env');

// cast to a boolean when the value is one of:
// "true", "false", "On", "Off", "Yes", "No", "1" and "0"
$boolean = $fDotEnv->castBoolean('MY_KEY');
$booleans = $fDotEnv->castBoolean(['MY_KEY1', 'MY_KEY2']);

// cast to an integer, including negative numbers
$integer = $fDotEnv->castInteger('MY_KEY');
$integers = $fDotEnv->castInteger(['MY_KEY1', 'MY_KEY2']);

Calling order

It doesn't matter which order you call the methods above in, they can be called before or after loading values from .env files. e.g.

$fDotEnv = FluentDotEnv::new()
    ->load('path/to/.env') // loaded at the beginning
    ->pick(['MY_KEY1', 'MY_KEY2'])
    ->integer('MY_KEY1')
    ->boolean('MY_KEY2')
    ->populateEnv();

$fDotEnv = FluentDotEnv::new()
    ->pick(['MY_KEY1', 'MY_KEY2']) // deferred
    ->integer('MY_KEY1') // deferred
    ->boolean('MY_KEY2') // deferred
    ->populateEnv() // deferred
    ->load('path/to/.env'); // loaded at the end

NOTE: When you call populateEnv() or populateServer() after load() has been called, the $_ENV and $_SERVER arrays respectively will be updated straight away.

Populating $_ENV and $_SERVER superglobals

By default, the $_ENV and $_SERVER superglobals are not changed when loading .env values.

However, you can choose to populate them by calling populateEnv(…) and populateServer(…) respectively. e.g.

$fDotEnv = FluentDotEnv::new()

    // add the loaded values to $_ENV
    ->populateEnv()
    // add values to $_ENV and override values that already exist
    ->populateEnv(true)

    // add the loaded values to $_SERVER
    ->populateServer()
    // add values to $_SERVER and override values that already exist
    ->populateServer(true)

    // the values are added when load is called
    ->load('path/to/.env');

Putenv() and getenv()

The putenv(…) and getenv(…) functions are not thread-safe, which may cause issues in a multi-threaded environment. For this reason this functionality is not included in this package. You can read discussion about this here and here.

NOTE: If you're using symfony/dotenv, you may want to consider using version 5.1.0 or higher…

symfony/dotenv added an option to turn off the use of putenv() in version 5.1.0. FluentDotEnv uses this to make sure the environment variables don't get changed. However, in earlier versions putenv() is used without a way to turn it off.

FluentDotEnv hides this away, leaving your environment variables the same as they were before loading. But, it means that environment variables are changed temporarily during the ->load() process.

Picking vlucas/phpdotenv or symfony/dotenv

You need to include either vlucas/phpdotenv or symfony/dotenv in your project:

composer require vlucas/phpdotenv
# or
composer require symfony/dotenv

FluentDotEnv will try to use vlucas/phpdotenv first, then symfony/dotenv.

If you have both installed and want to be particular about which one is used, you can call useVlucasPhpDotEnv() or useSymfonyDotEnv() before calling load(). e.g.

$fDotEnv = FluentDotEnv::new()
    ->useVlucasPhpDotEnv()
    ->load('path/to/.env');
$fDotEnv = FluentDotEnv::new()
    ->useSymfonyDotEnv()
    ->load('path/to/.env');

If neither are found, a CodeDistortion\FluentDotEnv\Exceptions\DependencyException will be thrown.

Testing This Package

  • Clone this package: git clone https://github.com/code-distortion/fluent-dotenv.git .
  • Run composer install to install dependencies
  • Run the tests: composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

SemVer

This library uses SemVer 2.0.0 versioning. This means that changes to X indicate a breaking change: 0.0.X, 0.X.y, X.y.z. When this library changes to version 1.0.0, 2.0.0 and so forth, it doesn't indicate that it's necessarily a notable release, it simply indicates that the changes were breaking.

Treeware

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Contributing

Please see CONTRIBUTING for details.

Code of Conduct

Please see CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email tim@code-distortion.net instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

code-distortion/fluent-dotenv 适用场景与选型建议

code-distortion/fluent-dotenv 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 104.43k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2020 年 07 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「config」 「wrapper」 「environment」 「env」 「dotenv」 「.env」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 code-distortion/fluent-dotenv 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 code-distortion/fluent-dotenv 我们能提供哪些服务?
定制开发 / 二次开发

基于 code-distortion/fluent-dotenv 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 104.43k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 21
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-07-15