PHP code example of initphp / console

1. Go to this page and download the library: Download initphp/console 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/ */

    

initphp / console example snippets


#!/usr/bin/env php


lication, Input, Output};

$console = new Application('My Console Application', '1.0.0');

// A closure command:  php console.php hello --name=John
$console->register('hello', function (Input $input, Output $output) {
    $output->writeln('Hello {name}!', [
        'name' => $input->getArgument('name', 'World'),
    ]);
}, 'Says hello.');

$console->run();

use InitPHP\Console\{Command, Input, InputArgument, Output};

class GreetCommand extends Command
{
    public $command = 'app:greet';

    public function definition(): string
    {
        return 'Greets a person.';
    }

    public function help(): string
    {
        return 'Prints a friendly greeting to the given name.';
    }

    public function arguments(): array
    {
        return [
            new InputArgument('name', InputArgument::STR, 'World', true, 'Who to greet.'),
        ];
    }

    public function execute(Input $input, Output $output)
    {
        $output->success('Hi ' . $input->getArgument('name'));
    }
}

$console->register(GreetCommand::class);

$output->writeln('Plain line');
$output->writeln('Coloured', [], [Output::COLOR_GREEN, Output::BOLD]);
$output->write('No newline; {token} interpolated', ['token' => 42]);

$output->error('Something failed');
$output->success('All good');
$output->warning('Heads up');
$output->info('FYI');

$output->list(['host' => 'localhost', 'port' => 8080]);

for ($i = 0; $i <= 100; $i += 10) {
    $output->progressBar($i, 100);
    usleep(50_000);
}

$name = $output->ask('What is your name?');

use InitPHP\Console\Question;

$question = (new Question())
    ->setQuestion('Continue? (yes/no)')
    ->setOptions(['yes', 'no'])
    ->optional()
    ->setDefault('no');

$answer = $output->question($question);

use InitPHP\Console\Utils\Table;

$table = Table::create()
    ->setHeaderStyle(Table::COLOR_RED, Table::BOLD)
    ->setBorderStyle(Table::COLOR_BLUE)
    ->setCellStyle(Table::COLOR_GREEN);

$table->row(['id' => 1, 'name' => 'Matthew S.', 'email' => '[email protected]', 'status' => true])
      ->row(['id' => 2, 'name' => 'Millie J.',  'email' => '[email protected]',  'status' => false]);

echo $table; // or $table->getContent()

// Before
use InitPHP\CLITable\Table;
// After
use InitPHP\Console\Utils\Table;
bash
php console.php hello --name=John   # Hello John!
php console.php hello               # Hello World!
php console.php list                # Show all registered commands
bash
php console.php app:greet --name=Ada
php console.php app:greet --help        # shows the generated usage + parameters