4 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.
01A command with options
cli_args() reads the program's arguments: --name=value options, --flag switches, -abc short flags and plain positional arguments. This tool greets everyone named on the command line.
01-arguments.hphp
<?php
import "cli";
$args = cli_args();
// usage help when nothing was given
if ($args->count() == 0 || $args->has("help")) {
echo "usage: greet [--greeting=Hello] [--shout] <name>...";
exit(1);
}
$greeting = $args->get("greeting", "Hello");
$shout = $args->has("shout");
// one line per positional argument
for ($i = 0; $i < $args->count(); $i++) {
$line = $greeting . ", " . $args->arg($i) . "!";
if ($shout) {
$line = strtoupper($line);
}
echo $line;
}
Try it
hphp run 01-arguments.hphp Ada Grace
hphp run 01-arguments.hphp --greeting=Hi --shout Ada
02An interactive setup
Asks a few questions like an installer would: free text with a default (cli_ask), a numbered menu (cli_choose) and a yes/no question (cli_confirm). Enter always keeps the value in brackets.
Lists the files of a folder, largest first, as an aligned table. cli_table() pads every column to its widest cell (colors do not count), so the output stays readable in any terminal.
hphp run 03-file-report.hphp
hphp run 03-file-report.hphp ../..
04A progress bar
cli_progress() returns the bar as a string; print it with a carriage return (\r) through printf so it redraws in place instead of adding a line each step.
04-progress.hphp
<?php
import "cli";
$steps = 40;
for ($i = 1; $i <= $steps; $i++) {
// pretend to work
usleep(50000);
// redraw the same line
printf("\r%s step %d/%d", cli_progress($i, $steps), $i, $steps);
}
echo "";
echo cli_color("done", "green");