定制 sodaho/env-loader 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

sodaho/env-loader

Composer 安装命令:

composer require sodaho/env-loader

包简介

Lightweight .env file loader for PHP

README 文档

README

Lightweight .env file loader for PHP. Zero dependencies.

Why This Library?

There are established .env loaders for PHP, most notably vlucas/phpdotenv. This library exists because we needed something simpler:

  • Zero dependencies — Nothing to install besides this package.
  • Thread-safe by design — Only writes to $_ENV. No putenv()/getenv(), which are not thread-safe in async runtimes (Swoole, RoadRunner, FrankenPHP).
  • No magic — No variable expansion (${VAR}), no multiline values, no interpreted escape sequences (\n, \t). What you write is what you get.
  • Minimal footprint — Easy to audit, easy to understand.

If you need variable expansion, multiline values, or getenv() support, use phpdotenv instead.

Installation

composer require sodaho/env-loader

Usage

Basic Usage

use Sodaho\EnvLoader\EnvLoader;

// Loads .env into $_ENV (does not overwrite existing, no required keys)
EnvLoader::load(__DIR__ . '/.env');

echo $_ENV['DB_HOST'];

Options

// Overwrite existing $_ENV variables
EnvLoader::load('.env', overwrite: true);

// Require specific keys (throws exception if missing)
EnvLoader::load('.env', required: ['DB_HOST', 'DB_NAME']);

// Required keys as comma-separated string
EnvLoader::load('.env', required: 'DB_HOST,DB_NAME');

// Combine options
EnvLoader::load('.env', overwrite: true, required: ['DB_HOST']);

Parse Without Loading

// Returns array without setting $_ENV
$values = EnvLoader::parse('.env');

print_r($values);
// ['DB_HOST' => 'localhost', 'DB_NAME' => 'myapp', ...]

Supported .env Syntax

# Comments
DB_HOST=localhost

# Empty values
EMPTY_VAR=

# Values with equals sign
PASSWORD=val=ue=with=equals

# Double quotes (supports escaped quotes)
MESSAGE="Hello World"
ESCAPED="Say \"Hello\""

# Single quotes (no escape processing)
SINGLE='Hello World'

# Inline comments
API_KEY=secret123 # this is ignored
QUOTED="value with # hash" # comment outside quotes

# export prefix
export DB_PORT=3306

# Whitespace is trimmed
  SPACED_KEY  =  value

Exceptions

All exceptions extend EnvLoaderException for easy catching:

use Sodaho\EnvLoader\EnvLoader;
use Sodaho\EnvLoader\Exception\EnvLoaderException;
use Sodaho\EnvLoader\Exception\FileNotFoundException;
use Sodaho\EnvLoader\Exception\MissingRequiredKeyException;

try {
    EnvLoader::load('.env', required: ['API_KEY']);
} catch (FileNotFoundException $e) {
    // File does not exist
} catch (MissingRequiredKeyException $e) {
    // Required key not found
} catch (EnvLoaderException $e) {
    // Any other EnvLoader error
}
Exception When
FileNotFoundException File does not exist or is a directory
FileNotReadableException File exists but not readable
InvalidKeyException Key has invalid format (e.g. 123KEY, MY-KEY)
UnterminatedQuoteException Quoted value missing closing quote
MissingRequiredKeyException Required key missing after loading

Key Naming Rules

Valid keys must:

  • Start with a letter or underscore
  • Contain only letters, numbers, and underscores
DB_HOST      ✓
_PRIVATE     ✓
API_KEY_2    ✓
123KEY       ✗ (starts with number)
MY-KEY       ✗ (contains hyphen)
MY KEY       ✗ (contains space)

Why $_ENV Only?

This library intentionally writes only to $_ENV, not putenv() or $_SERVER.

Reason: Thread Safety

putenv() and getenv() are not thread-safe. In modern PHP runtimes like:

  • Swoole
  • RoadRunner
  • FrankenPHP
  • ReactPHP

...concurrent requests can overwrite each other's environment variables, causing hard-to-debug race conditions.

$_ENV is process-local and safe. Use $_ENV['KEY'] instead of getenv('KEY') in your application.

// Safe
$host = $_ENV['DB_HOST'];

// Not recommended (not set by this loader)
$host = getenv('DB_HOST');

When to Use

  • Development environments
  • Shared hosting where system ENV is not available
  • Simple projects without framework
  • Modern async PHP (Swoole, RoadRunner, FrankenPHP)

When NOT to Use

  • Production with proper system ENV configuration
  • When you need variable expansion (${OTHER_VAR})
  • When you need multiline values
  • When you must support legacy code using getenv()

Requirements

  • PHP ^8.2

Acknowledgments

Parts of this project (refactoring, documentation, code review) were developed with AI assistance (Claude).

License

MIT

sodaho/env-loader 适用场景与选型建议

sodaho/env-loader 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 145 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 sodaho/env-loader 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 145
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 26
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-23