PHP code example of senhung / command-line-interface

1. Go to this page and download the library: Download senhung/command-line-interface library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

senhung / command-line-interface example snippets


$ php example <command>



enhung\CLI\CommandEntry;

/* Read through all commands in <change-folder-to-your-command-folder> */
CommandEntry::load('<change-folder-to-your-command-folder>');

/* When calling the script, execute the target command */
CommandEntry::entry($argv);




namespace Some\Name\Space;

use Senhung\CLI\Command;

class YourClassName extends Command
{
    /**
     * @var string $signature
     *
     * Set the signature of your command
     *
     * <command> how you call the command
     * {:arguments} arguments will be filled in in order when call
     * {--options} options are like flags or parameters
     */
    public $signature = '<command> {:arguments} {--options}';

    /**
     * @var string $description
     *
     * Description of your command
     *
     * Will be used in help command
     */
    public $description = 'Description for <command>';

    /**
     * The executing function when calling the command
     */
    public function handle()
    {
        /**
         * Write your handling function here
         *
         * You can get argument by: $this->getArgument('<argument-key>')
         * You can get option by: $this->getOption('<option-key>')
         */
    }
}


public $signature = '<command> {:arguments=some-default-value} {--options=some-default-value}';



/* file: example */

ry;

CommandEntry::load('Commands');

CommandEntry::entry($argv);




/* file: Commands/Greet.php */

namespace Example;

use Senhung\CLI\Command;

class Greet extends Command
{
    protected $signature = 'greet {:name} {--with-exclamation} {--number-of-times=1}';

    protected $description = 'Greet people';

    public function handle()
    {
        /* Repeat Greeting Times */
        $numberOfTimes = $this->getOption('number-of-times');

        /* Get Greeting Person's Name */
        $name = $this->getArgument('name');

        /* Check If Using Exclamation Point */
        $withExclamation = $this->getOption('with-exclamation');

        /* Repeat $numberOfTimes Times */
        for ($index = 0; $index < $numberOfTimes; $index++) {
            $greet = "Hello " . $name;

            if ($withExclamation) {
                $greet .= "!";
            }

            $greet .= "\n";

            echo $greet;
        }
    }
}

bash
$ php <entry-file-name> help
bash
$ php <entry-file-name> help <command>
bash
$ php example greet Senhung
bash
$ php example greet Senhung --with-exclamation