Understanding CLI Applications in PHP

CLI applications in PHP are executed through the command line, allowing developers to create scripts that can perform tasks directly in the terminal. PHP provides a built-in way to access command-line arguments via the $argv and $argc variables.

  • $argv: An array of arguments passed to the script.
  • $argc: The number of arguments passed to the script.

Basic CLI Application Structure

Let's start by creating a simple CLI application that accepts user input and performs a basic operation, such as adding two numbers.

<?php
// cli_app.php

if ($argc !== 3) {
    echo "Usage: php cli_app.php <number1> <number2>\n";
    exit(1);
}

$number1 = (float)$argv[1];
$number2 = (float)$argv[2];
$sum = $number1 + $number2;

echo "The sum of $number1 and $number2 is: $sum\n";

To run this script, execute the following command in your terminal:

php cli_app.php 5 10

This will output:

The sum of 5 and 10 is: 15

Argument Parsing with getopt()

For more complex applications, you may want to handle options and flags. PHP's getopt() function simplifies this process. Let's enhance our application to accept optional flags for verbose output.

<?php
// cli_app.php

$options = getopt("v::"); // -v for verbose

if ($argc < 3) {
    echo "Usage: php cli_app.php <number1> <number2> [-v]\n";
    exit(1);
}

$number1 = (float)$argv[1];
$number2 = (float)$argv[2];
$sum = $number1 + $number2;

if (isset($options['v'])) {
    echo "Verbose mode enabled.\n";
    echo "Calculating the sum...\n";
}

echo "The sum of $number1 and $number2 is: $sum\n";

Run the script with the verbose flag:

php cli_app.php 5 10 -v

Output:

Verbose mode enabled.
Calculating the sum...
The sum of 5 and 10 is: 15

Output Formatting

For better readability, consider using output formatting techniques. You can utilize PHP's printf() or sprintf() functions for formatted strings. Here’s how to format the output:

<?php
// cli_app.php

$options = getopt("v::");

if ($argc < 3) {
    echo "Usage: php cli_app.php <number1> <number2> [-v]\n";
    exit(1);
}

$number1 = (float)$argv[1];
$number2 = (float)$argv[2];
$sum = $number1 + $number2;

if (isset($options['v'])) {
    echo "Verbose mode enabled.\n";
    echo "Calculating the sum...\n";
}

printf("The sum of %.2f and %.2f is: %.2f\n", $number1, $number2, $sum);

Error Handling

Proper error handling is crucial for CLI applications. You can define custom error messages and exit codes to indicate different types of errors.

<?php
// cli_app.php

$options = getopt("v::");

if ($argc < 3) {
    fwrite(STDERR, "Error: Missing arguments. Usage: php cli_app.php <number1> <number2> [-v]\n");
    exit(1);
}

$number1 = (float)$argv[1];
$number2 = (float)$argv[2];

if (!is_numeric($number1) || !is_numeric($number2)) {
    fwrite(STDERR, "Error: Both arguments must be numbers.\n");
    exit(1);
}

$sum = $number1 + $number2;

if (isset($options['v'])) {
    echo "Verbose mode enabled.\n";
    echo "Calculating the sum...\n";
}

printf("The sum of %.2f and %.2f is: %.2f\n", $number1, $number2, $sum);

Best Practices for CLI Applications

  1. Use Clear and Consistent Naming: Follow naming conventions for your scripts and variables to enhance readability.
  2. Implement Help and Usage Instructions: Always provide users with instructions on how to use your CLI application.
  3. Validate Input: Ensure that user input is validated to prevent errors and unexpected behavior.
  4. Use Exit Codes: Return appropriate exit codes for different outcomes, making it easier to handle errors in scripts.

Conclusion

Building a custom CLI application in PHP can significantly enhance your development workflow. By leveraging argument parsing, output formatting, and error handling, you can create robust tools that streamline various tasks.

Learn more with useful resources