vlucas / phpdotenv

Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
BSD 3-Clause "New" or "Revised" License
13.15k stars 626 forks source link

How should this library be used when multiple dependencies of a project require it? #570

Open krytie75 opened 4 months ago

krytie75 commented 4 months ago

I'm confused about how this library should be used in the context of a project that uses (for example) Composer for dependancy management.

Take the example of ProjectA which has dependencies ProjectB and ProjectC. Let's say all three projects expect to obtain config/secrets via phpdotenv.

Should there be three .env files, one for each individual project and each project seperately calls Dotenv::CreateImmutable()? If so, where should those .env files go? In the individual project root dirs (which in deployment would be in the vendor dir)?

Or there should just be one .env file in the root of ProjectA which contains all of the env vars for all three projects?

In either case, what about env var name collisions? I can never guarantee that two externally developed dependencies won't be expecting values with the same key in the .env file and as they're not my projects I can't change the names.

I've ended up here because research seems to suggest using environment variables is now considered a 'best practise' approach but I just can't understand how it can possibly work unless I can guarantee full control over anything in my project that might require the use of them. I haven't been able to find any information about how to handle this sort of scenario so I'm hoping someone can enlighten me.

mlebkowski commented 2 weeks ago

Some time has passed since your question, but here’s my 2¢.

In my experience, you only use .env as a means to provide configuration to your main application (ProjectA in your example). If that app uses dependencies or libraries, most of the time they would either require explicit setup (think: new Dependency($configAlpha, $configBravo)), and on rare occasions they would specify additional environment variables you can use (like Guzzle will respect some proxy configuration and the AWS PHP SDK allows keeping credentials in env variables), but most certainly they will not automatically load and parse .env files to get those.

So in short: only use dotenv for top-level applications, and skip for libraries.