On a recent client project, I had a situation where a particular config value was needed in the CI pipeline, but there was an upcoming migration to a different CI provider, so they wanted an approach that worked in both environments.
The current CI provider gave us the value we needed in an environment variable, but we weren't quite sure if it could be obtained as easily in the new provider, so the fallback method involved a more expensive lookup.
Normally, if you want to provide a fallback to an environment variable in a config file, you'd do something like this:
'some_key' => env('SOME_ENV_VAR', expensiveLookupFunction()),
The problem with this approach is that PHP resolves the value of all function parameters before calling the function.
So even if SOME_ENV_VAR is set, PHP will still call expensiveLookupFunction(), which is wasteful.
One small change solves this problem nicely:
'some_key' => env('SOME_ENV_VAR') ?? expensiveLookupFunction(),
Notice that my expensive function is now outside the env() call.
It's on the other side of the null coalesce operator (??), so expensiveLookupFunction() is only called if SOME_ENV_VAR is not set, avoiding unnecessary work.
Perhaps you will find this pattern useful in your own project.
Here to help,
Joel
P.S. Can you tell I enjoy problem-solving? Let me help you the next time you get stuck.