The command design pattern is useful to create modular components for a command line shell application that can be expanded with more functionality implemented later by separate modules.
Run in console below command to download package to your project:
composer require degraciamathieu/clike
A command is a class that must implement the interface DeGraciaMathieu\Clike\Contracts\Command::class
.
The following example is a valid command.
use DeGraciaMathieu\Clike\Lines;
use DeGraciaMathieu\Clike\Contracts;
class Clear implements Contracts\Command {
/**
* Get the command description
*/
public function description() :string
{
return 'Command description...';
}
/**
* Check if the command is executable
*/
public function authorized() :bool
{
return true;
}
/**
* Bind of this command
*/
public function binding() :string
{
return '/clear';
}
/**
* Code executed by this command
*/
public function process() :void
{
//
}
/**
* Output of this command
*/
public function output() :array
{
return [
new Lines\Info('Output text...'),
];
}
}
Now let's play with our Clear command.
use DeGraciaMathieu\Clike\Command;
$command = new Command();
$command->execute(new Clear());
After checking that we can use this command with the authorized
method this code will execute the process
method of our command.
To finally execute the output
method displaying the following result.
// array:2 [
// "timestamp" => 1531339693
// "lines" => array:1 [
// 0 => array:2 [
// "type" => "info"
// "content" => "Output text..."
// ]
// ]
// ]
use DeGraciaMathieu\Clike\Terminal;
$terminal = new Terminal([
Clear::class,
]);
$terminal->execute('/clear');
use DeGraciaMathieu\Clike\Terminal;
$terminal = new Terminal([
Clear::class,
]);
$terminal->getAvailableCommands();
// [
// [
// "binding" => "/clear"
// "description" => "Command description..."
// ]
// ]