phpacker

Detecting Execution Context

PHPacker provides built-in environment detection so you can adapt your application's behavior based on whether it's running locally or in a build.

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'

Common Use Cases

This environment detection enables several powerful patterns:

  1. Error Handling : Display detailed error information during development while showing user-friendly error pages in production
  2. Performance Optimization : Enable caching and other optimizations in production while keeping development more dynamic
  3. 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();
}

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' conditional
if(getenv('PHPACKER_ENV') !== 'production')
//
}
 
// Detect the SAPI ('micro' in builds)
if(php_sapi_name() === 'micro')
//
}