Detecting Execution Context
Environment Detection
PHPacker automatically injects a
PHPACKER_ENV
environment variable into your application's runtime. This variable indicates whether your application is:
-
Running locally during development (
local
) -
Running from a compiled distribution binary (
production
)
You can access this variable using PHP's standard
getenv()
function:
$environment = getenv('PHPACKER_ENV'); // Returns 'local' or 'production'
$environment = getenv('PHPACKER_ENV'); // Returns 'local' or 'production'
Common Use Cases
This environment detection enables several powerful patterns:
- Error Handling : Display detailed error information during development while showing user-friendly error pages in production
- Performance Optimization : Enable caching and other optimizations in production while keeping development more dynamic
- Feature Toggling : Activate debugging tools or development-only features in local environments
Below you see a example on toggling the bootstrapping of the popular Collision package based on execution context:
use NunoMaduro\Collision\Provider; if(getenv('PHPACKER_ENV') === 'local') (new Provider)->register();}
use NunoMaduro\Collision\Provider; if(getenv('PHPACKER_ENV') === 'local') (new Provider)->register();}
Caveats
The environment variable will always be detected in
production
builds.
The
local
environment is always detected in apps that use the composer autoloader. However, without the autoloader present the environment is not automatically injected.
If this applies to you, please consider these alternatives:
// Inverting the 'production' conditionalif(getenv('PHPACKER_ENV') !== 'production') //} // Detect the SAPI ('micro' in builds)if(php_sapi_name() === 'micro') //}
// Inverting the 'production' conditionalif(getenv('PHPACKER_ENV') !== 'production') //} // Detect the SAPI ('micro' in builds)if(php_sapi_name() === 'micro') //}