This project demonstrates the use of modern invokable commands in Symfony 7.4, showcasing the reduction of boilerplate and enhanced type safety when building CLI tools.
-
Clone the repository:
git clone https://github.com/mattleads/InvokableCommands.git cd InvokableCommands -
Install dependencies:
composer install
The following examples highlight the new capabilities introduced in Symfony 7.4, including a custom #[ValidateInput] decorator for automatic DTO validation.
Symfony automatically validates and maps input values to PHP Backed Enums for command arguments.
Valid Usage:
php bin/console app:create-server us-east-1
# Output: Creating server in region: us-east-1Invalid Usage:
php bin/console app:create-server mars
# Output: [ERROR] The value "mars" is not allowed for argument "region".
# Allowed values are: "us-east-1", "eu-central-1", "ap-northeast-1".Command arguments and options are mapped to a DTO. Using our custom #[ValidateInput] decorator, Symfony's Validator component automatically checks the DTO constraints before the command runs.
Valid Usage:
php bin/console app:deploy-server eu-central-1 --size=medium
# Output: Deploying medium instance to eu-central-1...Invalid Usage (Validation Failure):
php bin/console app:deploy-server us-east-1 --size=huge
# Output: [ERROR] Validation failed for command input:
# - size: The value you selected is not a valid choice.Demonstrates combining #[MapInput], #[ValidateInput], and custom #[Interact] logic.
Valid Usage (Direct):
php bin/console app:report:generate sales --period=monthly --format=csv --email=test@test.com
# Output: Report generated. Sent to test@test.comValid Usage (Interactive):
php bin/console app:report:generateFor simple cases where a missing argument should prompt the user for input, use the #[Ask] attribute directly on the parameter.
Valid Usage (Direct):
php bin/console app:hello Alice
# Output: Hello, Alice!Valid Usage (Interactive):
php bin/console app:hello
# Prompts: What is your name? (User types "Bob")
# Output: Hello, Bob!For complex interactive flows (like hidden password prompts), the #[Interact] attribute marks a method as an interaction handler.
Valid Usage (Direct):
php bin/console app:wizard my-secret-key
# Output: Password received (hashed): <md5_hash>Valid Usage (Interactive):
php bin/console app:wizard
# Prompts: Please enter your API password (User types "hidden-input")
# Output: Password received (hashed): <md5_hash>