Building CLI Utilities with PHP
PHP isn't limited to serving web pages. The CLI SAPI allows you to craft scripts that handle background jobs, system maintenance and developer tooling. In this guide you'll build a simple command line utility.
Parsing arguments
Use the $argv array to access command line arguments. The first element is the script name, subsequent elements are the passed parameters:
<?php
declare(strict_types=1);
if ($argc < 2) {
fwrite(STDERR, "Usage: php greet.php <name>\n");
exit(1);
}
$name = $argv[1];
echo "Hello, $name!\n";
?>
Run the script from your terminal: php greet.php Alice and you will see a greeting printed to STDOUT.
Creating reusable commands
For more complex tools, encapsulate commands into classes and use a dispatcher. Here's a basic example:
<?php
declare(strict_types=1);
interface Command { public function execute(array $args): void; }
class SayHello implements Command {
public function execute(array $args): void {
$name = $args[0] ?? 'World';
echo "Hello, $name!\n";
}
}
$commands = [
'hello' => new SayHello(),
];
$cmd = $argv[1] ?? null;
if (!$cmd || !isset($commands[$cmd])) {
fwrite(STDERR, "Available commands: hello\n");
exit(1);
}
array_shift($argv); // remove script name
array_shift($argv); // remove command
$commands[$cmd]->execute($argv);
?>
This pattern sets the foundation for a robust CLI utility with multiple subcommands.