Skip to content
Oliver edited this page Jun 9, 2023 · 10 revisions

Install

To install the CLIFramework package, run the command below.

composer require "corneltek/cliframework"

If you don't have composer set up yet, run composer init first, add the following to your composer.json file and then run the command above.

{
    ...,
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "minimum-stability": "dev",
    ...
}

Create the application

The application is the starting point of your command line interface. Start by defining the application.

app/Console.php

namespace App;
use CLIFramework\Application;

class Console extends Application
{
    /* register your command here */
    public function init()
    {
        parent::init(); // Standard commands
        $this->command('now', Commands\NowCommand::class); // Custom commands
    }
}

Create the command

Then define your command class:

app/Commands/NowCommand.php

namespace App\Commands;

use CLIFramework\Command;
use DateTime;
use DateTimeInterface;

class NowCommand extends Command {
    public function brief()
    {
        return "Displays current date and time."; //Short description
    }

    public function execute()
    {
        // Print current date and time.
        $this->getLogger()->writeln((new DateTime())->format(DateTimeInterface::RFC7231));
    }
}

Run

In order to run the software from the command line, you'll have to create a php script that calls the application you defined.

program.php

<?php
require 'vendor/autoload.php'; // Only if autoload is not set up already.
$app = new \App\Console;
$app->runWithTry($argv); // $argv is a global variable containing command line arguments.

Then, to test your application:

php program.php help
php program.php now