PHP LogoCommand Line Interface (CLI) Applications

Command Line Interface (CLI) Applications are programs that users interact with primarily through text commands in a terminal or console window, rather than a graphical user interface (GUI). They are fundamental tools for system administration, software development, automation, and server-side operations.

Why use CLI applications?
* Automation and Scripting: CLIs are ideal for scripting repetitive tasks, allowing them to be executed automatically without human intervention.
* Resource Efficiency: They typically consume fewer system resources (CPU, RAM) compared to GUI applications because they don't render graphical elements.
* Remote Access: CLIs are indispensable for managing remote servers, often accessed via SSH, where a graphical environment might not be available or practical.
* Speed and Productivity: For experienced users, typing commands can often be faster and more efficient than navigating menus and clicking buttons in a GUI.
* Interoperability: CLI tools can be easily chained together using pipes (`|`) and redirects (`<`, `>`) to create complex workflows.

Key Concepts in PHP CLI Development:
1. `$argv` and `$argc`: These are superglobal variables automatically populated when a PHP script is run from the command line.
* `$argv`: An array containing all the command-line arguments passed to the script. The first element (`$argv[0]`) is always the name of the script itself.
* `$argc`: An integer representing the number of arguments passed to the script (i.e., the size of the `$argv` array).
2. Input/Output (I/O):
* Standard Output (STDOUT): Used for printing normal program output (e.g., `echo`, `print_r`).
* Standard Error (STDERR): Used for printing error messages (e.g., `fwrite(STDERR, "Error message\n")`).
* Standard Input (STDIN): Used for reading user input (e.g., `fgets(STDIN)`).
3. Exit Codes: Programs should return an exit code to indicate their success or failure. `0` conventionally indicates successful execution, while non-zero values (e.g., `1`, `255`) indicate an error or specific problem. In PHP, `exit(0);` or `exit(1);` can be used.
4. Options and Flags: Arguments often come as short flags (e.g., `-v` for verbose) or long options (e.g., `--version`, `--help`). Parsing these requires careful handling of `$argv`.
5. Helper Libraries/Frameworks: For more complex CLI applications, frameworks like Symfony Console or Laravel Artisan (built on Symfony Console) provide robust tools for argument parsing, command structuring, interactive prompts, progress bars, and colored output, significantly simplifying development.

Basic Structure of a PHP CLI Script:
A PHP CLI script is essentially a regular PHP file that is executed from the command line using the PHP interpreter (e.g., `php your_script.php arg1 arg2`). It typically starts with a shebang line (`#!/usr/bin/env php`) on Unix-like systems to make it directly executable, followed by the PHP code that processes arguments and performs actions.

Example Code

#!/usr/bin/env php
<?php

// greeter.php - A simple CLI greeter application

/
 * Displays the help message for the application.
 */
function showHelp()
{
    echo "Usage: php greeter.php <command> [name] [--help]\n";
    echo "\n";
    echo "Commands:\n";
    echo "  hello    Greets the specified name. If no name is provided, greets 'World'.\n";
    echo "  goodbye  Bids farewell to the specified name. If no name is provided, bids farewell to 'World'.\n";
    echo "\n";
    echo "Options:\n";
    echo "  --help   Display this help message.\n";
    echo "\n";
    echo "Examples:\n";
    echo "  php greeter.php hello\n";
    echo "  php greeter.php hello Alice\n";
    echo "  php greeter.php goodbye Bob\n";
    exit(0); // Indicate success after showing help
}

// Get all arguments passed to the script
$args = $argv;
// Remove the script name itself from the arguments list
array_shift($args);

// Check if --help flag is present
if (in_array('--help', $args)) {
    showHelp();
}

// Ensure at least one command is provided
if (empty($args)) {
    fwrite(STDERR, "Error: No command provided. Use 'php greeter.php --help' for usage.\n");
    exit(1); // Indicate error
}

$command = array_shift($args); // The first remaining argument is the command
$name = empty($args) ? 'World' : array_shift($args); // The next argument is the name, default to 'World'

switch ($command) {
    case 'hello':
        echo "Hello, $name!\n";
        break;
    case 'goodbye':
        echo "Goodbye, $name!\n";
        break;
    default:
        fwrite(STDERR, "Error: Unknown command '$command'. Use 'php greeter.php --help' for usage.\n");
        exit(1); // Indicate error
}

exit(0); // Indicate successful execution

?>