Prepping your CLI app
Single PHP Script Limitations
If you're building from a single PHP script, all code must be contained within that file. External dependencies through require or use statements are not supported. If your application needs external dependencies, you should first package it as a PHAR archive using a tool like humbug/box .
File System Access
When your application is packaged (either from a single script or PHAR), it cannot write files within the application itself since everything is combined into a single executable. Instead, use the platform-specific application data directory for file storage. Here's a helper script to determine the correct path:
use Symfony\Component\Filesystem\Path; $appName = 'my-app'; // Define APP_DATA constantdefine('APP_DATA', match (PHP_OS_FAMILY) { 'Darwin' => Path::join(getenv('HOME'), 'Library', 'Application', 'Support', ".{$appName}"), 'Windows' => Path::join(getenv('LOCALAPPDATA'), $appName), default => Path::join(getenv('HOME'), ".{$appName}"))});
use Symfony\Component\Filesystem\Path; $appName = 'my-app'; // Define APP_DATA constantdefine('APP_DATA', match (PHP_OS_FAMILY) { 'Darwin' => Path::join(getenv('HOME'), 'Library', 'Application', 'Support', ".{$appName}"), 'Windows' => Path::join(getenv('LOCALAPPDATA'), $appName), default => Path::join(getenv('HOME'), ".{$appName}"))});
This ensures your application's data is stored in the appropriate location across different operating systems:
- macOS: ~/Library/Application Support/.my-app
- Windows: %LOCALAPPDATA%\my-app
- Linux: ~/.my-app
Additional Application Considerations
-
Environment variables
: Access environment variables using the standard
getenv()
function or$_ENV
superglobal -
Temporary files
: Use
sys_get_temp_dir()
to get the system's temporary directory for temporary file operations - Command line arguments : Use a library for robust CLI argument handling. Like symfony/console , laravel-zero or minicli