Revision: Fri, 31 May 2024 16:10:57 GMT

Getting started — First CLI command

Spiral offers a convenient approach to creating console applications. It comes with built-in support for console commands, enabling you to develop command-line interfaces (CLIs) for your application. Console commands empower you to automate tasks, perform maintenance operations, and interact with your application in ways beyond the limitations of a standard web interface.

Working with console commands in Spiral is incredibly straightforward. The framework provides a user-friendly interface that leverages the power of the symfony/console package.

Let's walk through the basic steps of creating a console command.

Creating a command

To create your first command effortlessly, use the scaffolding command:

php app.php create:command CurrentDate

Read more about scaffolding in the Basics — Scaffolding section.

After executing this command, the following output will confirm the successful creation:

Declaration of 'CurrentDateCommand' has been successfully written into 'app/src/Endpoint/Console/CurrentDateCommand.php'.

Now, let's inject some logic into our freshly created command.

Here's an example of a console command that outputs current date to the console:

namespace App\Endpoint\Console;

use Spiral\Console\Attribute\Argument;
use Spiral\Console\Attribute\AsCommand;
use Spiral\Console\Attribute\Option;
use Spiral\Console\Attribute\Question;
use Spiral\Console\Command;

#[AsCommand(name: 'current:date')]
final class CurrentDateCommand extends Command
    #[Argument(description: 'Date format')]
    public string $format = 'Y-m-d';

    public function __invoke(): int

        return self::SUCCESS;

By default, Spiral is configured to automatically discover commands located in the app/src directory through the static analysis component. This means you don't have to manually register your commands or create a separate configuration file for them.

Running the command

To retrieve help information for your command, execute the following command in your terminal:

php app.php help current:date

This will display the command's signature, description, and any available arguments or options.

Get current date
current:date [<format>]
format Date format [default: "Y-m-d"]
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

That's it! You have successfully set up your first console command in Spiral.

What's Next?

Now, dive deeper into the fundamentals by reading some articles: