Skip to content

Commit 3995060

Browse files
update to version 2 (#2)
1 parent c816582 commit 3995060

31 files changed

+1590
-2400
lines changed

.gitignore

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
.idea/
22

33
# phpunit generated files
4-
.phpunit.cache
5-
build/
4+
phpunit/
65

76
vendor/
7+
8+
composer.lock

CHANGELOG.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,27 @@ $dotenv->reload(); // Reload no longer accept default values
6767
$dotenv->has('APP_LOCALE');
6868
```
6969
- You can now control whether to overwrite existing environment variables when loading multiple env files, via the $overwrite parameter.
70+
71+
## v2.0.0
72+
73+
### 🚀 Added
74+
- **JSON File Support** — Load environment variables from structured `.json` files.
75+
- **Custom Loader Registry** — Add support for user-defined loaders (e.g., YAML, XML).
76+
- **Static Access** — Access env values directly using `Env::get()` or `Env::group()`.
77+
- **Safe Loading** — Use `safeLoad()` to avoid exceptions on missing or malformed files.
78+
- **Multiple File Support** — Load multiple `.env` and `.json` files in defined order.
79+
- **Caching** — Enable in-memory caching for performance using `cache: true`.
80+
- **LoaderRegistry** — Convention-based class resolution for parsers like `JsonParser`.
81+
82+
### 🛠️ Changed
83+
- `Env::create()` no longer loads `.env` by default — use `->load()` explicitly.
84+
- Parser resolution now follows a naming convention (`JsonParser`, `YamlParser`, etc.).
85+
- Parser must implement `ParserInterface` and be registered for custom loaders.
86+
87+
### ⚠️ Breaking Changes
88+
- The legacy `$dotenv = new Dotenv(...)->load()` style is replaced by `Env::create(...)->load()`.
89+
- Parser resolution and loader registration are now required for custom file formats.
90+
91+
### ✅ Internal Improvements
92+
- Improved performance by using `fopen()` instead of `file()` for reading files.
93+
- Cleaner architecture with `BaseLoader`, `LoaderInterface`, and `LoaderRegistry`.

README.md

Lines changed: 107 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,26 @@
88
</div>
99

1010
## About
11-
The `NAL\Dotenv` class is a lightweight PHP package for managing environment variables.
12-
It allows you to load environment variables from files, group variables, and access them in your PHP application.
13-
The class supports loading variables from multiple files.
11+
`NAL\Dotenv` is a flexible and lightweight PHP environment loader designed for modern applications.
12+
It supports loading environment variables from `.env` and `.json` files by default, with the ability to register custom loaders (e.g., YAML, XML) effortlessly.
13+
14+
**This package provides:**
15+
16+
- Grouped access to related environment keys
17+
- Support for multiple environment files
18+
- Static or instance-based access
19+
- Optional caching for performance
20+
- Convention-based parser resolution
21+
- Seamless integration with custom loaders and parsers
22+
23+
It's ideal for both small-scale projects and larger applications where managing structured and multi-source environment data is essential.
1424

1525
## Contributing
1626
- This is an open-source library, and contributions are welcome.
1727
- If you have any suggestions, bug reports, or feature requests, please open an issue or submit a pull request on the project repository.
1828

1929
## Requirement
20-
- **PHP** version 8.0 or newer is required
30+
- **PHP** version 8.2 or newer is required
2131

2232
## Installation & Setup
2333

@@ -44,122 +54,136 @@ composer require naingaunglwin-dev/dotenv
4454
```
4555

4656
## Features
57+
**Load .env files easily**
58+
- Supports standard .env key-value files for environment configuration.
4759

48-
- ✅ Automatically uses the project root, but allows setting a custom path when initializing.
49-
- ✅ Load from multiple .env files
50-
- ✅ Customize file names and base path
51-
- ✅ Support for grouped environment variables
52-
- ✅ Auto-sync with `$_ENV`, `$_SERVER`, and `getenv()`
53-
- ✅ Reload environment at runtime
54-
- ✅ Check if a variable exists with `has()`
55-
- ✅ Supports default fallback values
60+
**Support for .json config files**
61+
- Load structured environment data from JSON files — great for frontend-backend monorepo setups.
5662

57-
## Constructor Signature
58-
```php
59-
public function __construct(
60-
array|string|null $files = null,
61-
string|null $envKey = null,
62-
bool $overwrite = true
63-
)
64-
```
65-
- `$files`: Optional string or array of .env file names. Defaults to standard files like `.env`, `.env.local`, etc.
66-
- `$envKey`: Custom key for detecting the app environment (e.g., `APP_ENV`)
67-
- `$overwrite`: Whether to overwrite existing variables (true by default)
68-
69-
70-
- If no file is provided, the Dotenv class will search for the following default files in root directory:
71-
- .env
72-
- .env.local,
73-
- .env.development
74-
- .env.production
75-
- .env.testing
76-
- .env.dev
77-
- .env.prod
78-
- .env.test
79-
- .env.staging
63+
**Nested key flattening**
64+
- Nested JSON keys are automatically flattened into uppercase ENV_STYLE_KEYS.
8065

81-
## Usage
66+
**Environment grouping support**
67+
- Automatically organizes keys into groups based on naming conventions like APP_ENV → APP group.
8268

83-
### Loading Environment Variables
84-
- You can pass your environment file(s) with either a full path or just the file name.
85-
- If you pass a full path, the file will be loaded directly from that path.
86-
- If you pass just the file name, it will be resolved relative to the project root directory.
69+
**Custom Loader Registry**
70+
- Register your own loaders to support formats like YAML, TOML, etc.
71+
72+
**Optional override behavior**
73+
- Configure whether later files can override previously loaded keys.
74+
75+
**Safe loading**
76+
- Use `safeLoad()` to prevent exceptions when loading optional or missing files.
77+
78+
**Supercharged access methods**
79+
- Access environment values using `Env::get('KEY')` or grouped access with `Env::group('APP')`.
80+
81+
**Supports multiple files**
82+
- Pass an array of files to load them in order — useful for layering config.
83+
84+
## Usage
8785

8886
```php
8987
<?php
9088

91-
use NAL\Dotenv\Dotenv;
92-
93-
// Load a file using its full path
94-
$dotenv = new Dotenv('/home/user/project/config/.env.custom');
89+
use NAL\Dotenv\Env;
9590

96-
// Load a file from the project root by name
97-
$dotenv = new Dotenv('.env.production');
91+
$env = Env::create()->load();
9892

99-
// Load multiple files
100-
$dotenv = new Dotenv(['.env.local', '/home/user/project/.env.override']);
93+
// Access values
94+
$envs = $env->get('APP_ENV'); // "production"
95+
$group = $env->group('DATABASE'); // ['DATABASE_HOST' => '127.0.0.1', ...]
10196
```
10297

103-
### Accessing Environment Variables
104-
98+
#### Static Access
99+
You can also use static calls without manually creating an instance:
105100
```php
106-
// Get a specific variable
107-
$dotenv->load();
101+
<?php
102+
103+
use NAL\Dotenv\Env;
108104

109-
$host = $dotenv->get('DB_HOST'); // Get a variable
110-
$debug = $dotenv->get('DEBUG', false); // With fallback
111-
$all = $dotenv->get(); // Get all loaded variables
105+
$value = Env::get('APP_ENV');
106+
$group = Env::group('APP');
112107
```
108+
> If no instance was created yet, Env::get() and Env::group() will auto-initialize using default behavior `(.env, no cache)`. If an instance was previously created via Env::create(), the static calls will reuse that instance instead.
113109
114-
### Check Existence
110+
#### Safe Load (No Exceptions)
115111
```php
116-
if ($dotenv->has('APP_SECRET')) {
117-
// APP_SECRET is defined
118-
}
119-
```
112+
<?php
120113

121-
### Grouping Environment Variables
122-
- You can access grouped environment variables with the group() method.
123-
- This can be useful if you have variables structured by prefix (e.g., APP_NAME, APP_ENV).
114+
use NAL\Dotenv\Env;
115+
116+
$env = Env::create()->safeLoad(); // Returns ['envs' => [], 'groups' => []] on failure
117+
```
124118

119+
#### Load JSON Configuration
125120
```php
126-
$grouped = $dotenv->group('APP');
127-
// e.g., ['APP_NAME', 'APP_ENV', 'APP_KEY']
121+
<?php
122+
123+
use NAL\Dotenv\Env;
124+
125+
$env = Env::create(name: 'env.json')->load();
128126
```
129127

130-
### Reloading Environment Variables
131-
- You can reload environment variables by calling the `reload()` method. This method clears the previously loaded variables and reloads them from the specified files.
128+
#### Load Multiple Files
132129
```php
133-
$dotenv->reload(); // Clear and reload loaded files
130+
<?php
131+
132+
use NAL\Dotenv\Env;
133+
134+
Env::create(name: ['.env', '.env.testing'])->load();
134135
```
135136

136-
## Exception Handling
137-
- The Dotenv class throws the following exceptions:
137+
#### Enable Caching
138+
```php
139+
<?php
138140

139-
- **NAL\Dotenv\Exception\Missing**: Thrown when the specified environment file does not exist.
140-
- **NAL\Dotenv\Exception\UnMatch**: Thrown when an environment variable key does not match the expected format.
141+
use NAL\Dotenv\Env;
141142

142-
### Example
143+
Env::create(name: '.env', cache: true)->load(); // Loads once, reuses from memory
144+
```
145+
146+
#### Register Custom Loader (e.g., YAML)
143147
```php
144148
<?php
145149

146-
use NAL\Dotenv\Dotenv;
150+
use NAL\Dotenv\Loader\LoaderRegistry;
147151

148-
try {
149-
$dotenv = new Dotenv(['.env']);
150-
$dotenv->load();
152+
$registry = new LoaderRegistry();
151153

152-
$dbUser = $dotenv->get('DB_USER', 'root');
154+
$registry->register('yaml', fn ($file, $override, $resolver, $parser) => new YamlLoader(
155+
$file, $override, $resolver, $parser
156+
), '\\Namespace\\For\\Parser');
153157

154-
} catch (\Exception $e) {
155-
echo 'Dotenv Error: ' . $e->getMessage();
156-
}
158+
Env::create(name: 'config.yaml', registry: $registry)->load();
157159
```
158160

161+
**Notes for Custom Loader Development**
162+
- The registered callback must accept exactly 4 arguments in this order:
163+
```php
164+
($file, $override, $resolver, $parser)
165+
```
166+
- Your custom loader **must**:
167+
168+
- Implement `NAL\Dotenv\Loader\LoaderInterface`
169+
170+
**or**
171+
172+
- Extend `NAL\Dotenv\Loader\BaseLoader` for convenient utilities like `resolveFiles()` and `save()`.
173+
174+
- Every custom loader must include a corresponding parser, whose class name:
175+
176+
- **Starts with the capitalized extension name**, followed by Parser
177+
**e.g., for .yaml, the parser must be YamlParser**
178+
179+
- **Must implement** `NAL\Dotenv\Parser\ParserInterface`
180+
181+
> Parsers are resolved by convention from the namespace `\NAL\Dotenv\Parser\`, or a custom namespace if provided.
182+
159183
## Running Tests
160184

161185
- To run the test suite, execute the following command
162186
```bash
163-
vendor/bin/phpunit tests/DotenvTest.php
187+
vendor/bin/phpunit tests/EnvTest.php
164188
```
165-
- This will run all test cases defined in the DotenvTest.php file.
189+
- This will run all test cases defined in the EnvTest.php file.

composer.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
{
22
"name": "naingaunglwin-dev/dotenv",
3-
"description": "Simple PHP Dotenv Library",
3+
"description": "Simple and lightweight php dotenv library",
44
"minimum-stability": "dev",
5-
"version": "1.0.3",
5+
"version": "2.0.0",
66
"prefer-stable": true,
77
"license": "MIT",
88
"authors": [
@@ -21,6 +21,6 @@
2121
}
2222
},
2323
"require-dev": {
24-
"phpunit/phpunit": "^12.1"
24+
"phpunit/phpunit": "^11.5"
2525
}
2626
}

0 commit comments

Comments
 (0)