Skip to content

[Console] Add support for invokable commands and input attributes #59340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 10, 2025

Conversation

yceruto
Copy link
Member

@yceruto yceruto commented Dec 31, 2024

Q A
Branch? 7.3
Bug fix? no
New feature? yes
Deprecations? yes
Issues -
License MIT

Alternative to: #57225

This PR focuses on enhancing the DX for creating and defining console commands.

Key improvements include:

  • No Need to Extend the Command Class: When using an invokable class marked with #[AsCommand], extending the Command class is no longer required.
  • Automatic Argument and Option Inference: Command arguments and options are now inferred directly from the parameters of the __invoke() method, thanks to the new #[Argument] and #[Option] attributes.
  • Flexible __invoke() Signature: The __invoke() method now has a flexible signature, allowing you to define only the helpers you need. Also, this method will fallback to 0 (success) if you return void It's required to return an int value as result, see [Console] Deprecate returning a non-int value from a \Closure function set via Command::setCode() #60076 .

Before

#[AsCommand(name: 'lucky:number')]
class LuckyNumberCommand extends Command
{
    public function __construct(private LuckyNumberGenerator $generator)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument('name', InputArgument::REQUIRED);
        $this->addOption('formal', null, InputOption::VALUE_NONE | InputOption::VALUE_NEGATABLE);
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $formal = (bool) $input->getOption('formal');
        $name = $input->getArgument('name');

        $io->title(sprintf('%s %s!', $formal ? 'Hello' : 'Hey', ucfirst($name)));
        $io->success(sprintf('Today\'s Lucky Number: %d', $this->generator->random()));

        return 0;
    }
}

After

#[AsCommand(name: 'lucky:number')]
class LuckyNumberCommand
{
    public function __construct(private LuckyNumberGenerator $generator)
    {
    }

    public function __invoke(SymfonyStyle $io, #[Argument] string $name, #[Option] bool $formal = false): int
    {
        $io->title(sprintf('%s %s!', $formal ? 'Hello' : 'Hey', ucfirst($name)));
        $io->success(sprintf('Today\'s Lucky Number: %d', $this->generator->random()));

        return 0;
    }
}

However, you can still extend the Command class when necessary to use advanced methods, such as the interact() method and others.

Happy New Year! 🎉

@yceruto yceruto requested a review from chalasr as a code owner December 31, 2024 19:22
@carsonbot carsonbot added Status: Needs Review Console DX DX = Developer eXperience (anything that improves the experience of using Symfony) Feature labels Dec 31, 2024
@carsonbot carsonbot added this to the 7.3 milestone Dec 31, 2024
@carsonbot carsonbot changed the title [Console][DX] Add support for invokable commands and input attributes [Console] Add support for invokable commands and input attributes Dec 31, 2024
@yceruto yceruto requested a review from kbond December 31, 2024 19:28
Copy link
Member

@kbond kbond left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really great @yceruto!

Not required for this PR but just some ideas:

  1. Allow #[AsCommand] to be added to public methods (I believe this can be added easily).
  2. #[AsCommand] on methods in your kernel - for micro-apps.

🥂 Happy new year!

Copy link
Member

@GromNaN GromNaN left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love it 💚

  1. Allow #[AsCommand] to be added to public methods (I believe this can be added easily).
  2. #[AsCommand] on methods in your kernel - for micro-apps.

I think we should go all the way with this principle and only look for the AsCommand attribute on service methods.

This would make it possible to define several commands in a single class, or a command directly on a service class.

It could be so flexible that it could quickly become chaotic on some projects; we might need a debug:console command to find the callable associated to each command.

@94noni
Copy link
Contributor

94noni commented Jan 1, 2025

I like it a lot, it reminds me #49522
just a question, does this competes/supersedes #57225 ?
Cheers

@OskarStark
Copy link
Contributor

cc @kbond as you are the author of

https://github.com/zenstruck/console-extra

@yceruto
Copy link
Member Author

yceruto commented Jan 1, 2025

cc @kbond as you are the author of
https://github.com/zenstruck/console-extra

We had a chat recently about this topic and that repo was my inspiration actually

@yceruto yceruto force-pushed the simpler_command branch 3 times, most recently from d8a8a6d to aafa900 Compare January 1, 2025 20:02
@yceruto
Copy link
Member Author

yceruto commented Jan 1, 2025

I've tested the Symfony one-file demo with this approach for a single-app command, and this is the result:

<?php

require_once __DIR__.'/vendor/autoload_runtime.php';

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpKernel\Kernel;

#[AsCommand('app:start')]
class SymfonyOneFileApp extends Kernel
{
    use MicroKernelTrait;

    public function __invoke(SymfonyStyle $io, #[Argument] string $name = 'World'): void
    {
        $io->success(sprintf('Hello %s!', $name));
    }
}

return static function (array $context) {
    return new Application(new SymfonyOneFileApp($context['APP_ENV'], (bool) $context['APP_DEBUG']));
};

It's missing having services autowired on the method, though.

@yceruto
Copy link
Member Author

yceruto commented Jan 1, 2025

I like it a lot, it reminds me #49522
just a question, does this competes/supersedes #57225 ?
Cheers

@94noni They are related yes. I'm waiting for a deeper conversation with @chalasr to get more insights about the work he is doing in this regard, but in theory this should close & replace those proposals.

@smnandre
Copy link
Member

smnandre commented Jan 1, 2025

I love it! Really nice DX addition 👏

@yceruto
Copy link
Member Author

yceruto commented Jan 2, 2025

I’ve concerns about supporting #[AsCommand] on public methods and allowing multiple commands on the same class/instance:

  • when extending from the Command class, methods like isEnabled(), interact(), or initialize() will respond to all commands defined in that class, which is undesirable
  • when not extending from the Command class, there is currently no way to inspect methods with the #[AsCommand] attribute unless we also repeat #[AsCommand] on the class itself (for autoconfiguration/tagging) not true, it's actually supported
  • last but not least, it won’t align with the SRP

I don't think it's a good idea to support that


if (\is_array($self->suggestedValues) && !\is_callable($self->suggestedValues) && 2 === \count($self->suggestedValues) && ($instance = $parameter->getDeclaringFunction()->getClosureThis()) && $instance::class === $self->suggestedValues[0] && \is_callable($instance::class, $self->suggestedValues[1])) {
$self->suggestedValues = [$instance, $self->suggestedValues[1]];
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[note for reviewer] this falls back from the "static class method call" syntax to the "object method call" syntax due to the impossibility of passing a \Closure or callable in the attribute constructor. Allowing this suggestion methods to access the instance's dependencies.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For instance, this will allow us to configure #[Argument(suggestedValues: [self::class, 'getPermissions'])] where getPermissions is not defined as static method, enabling it to access any instance dependencies and dynamically retrieve all available permissions from another service (e.g. entity manager)

@GromNaN
Copy link
Member

GromNaN commented Jan 2, 2025

I’ve concerns about supporting #[AsCommand] on public methods and allowing multiple commands on the same class/instance:

  • when extending from the Command class, methods like isEnabled(), interact(), or initialize() will respond to all commands defined in that class, which is undesirable

Let's just say that these functions are rarely used in final projects, and that if you want to use them, it's worth separating the commands into separate classes.

  • when not extending from the Command class, there is currently no way to inspect methods with the #[AsCommand] attribute unless we also repeat #[AsCommand] on the class itself (for autoconfiguration/tagging)

To quote @stof:

The registerAttributeForAutoconfiguration method inspects the parameter type of the configuration callback to discover which source need to be inspected.

  • last but not least, it won’t align with the SRP

SRP is an implementation principle that can be left up to the developer. I once had 2 commands that were functionally very close to each other, but with different arguments. To share part of the code between the 2, I needed an abstract class. With this new approach, I can create 2 commands in 1 class instead of 3.

What I like about it is the ease with which you can create new commands with just a little code. A little RAD, no doubt, but ultimately very useful.

@yceruto
Copy link
Member Author

yceruto commented Jan 2, 2025

I’ve concerns about supporting #[AsCommand] on public methods and allowing multiple commands on the same class/instance:

when extending from the Command class, methods like isEnabled(), interact(), or initialize() will respond to all commands defined in that class, which is undesirable

Let's just say that these functions are rarely used in final projects, and that if you want to use them, it's worth separating the commands into separate classes.

Yeah, it's an unhappy situation in my opinion. Just imagine you already have two commands in the same class, then you decide to use the interact() method (or any of those methods), and the framework tells you to split that class; otherwise, there is an ambiguity.

I'd prefer to guide developers to happy paths where the code can evolve without problems, even if that implies adding one class per command, which is easier than before now.

@yceruto yceruto force-pushed the simpler_command branch 2 times, most recently from 9873de3 to 14e8332 Compare January 2, 2025 15:03
@tacman
Copy link
Contributor

tacman commented Jan 3, 2025

Woo hoo! I love https://github.com/zenstruck/console-extra, I recently ported some older code and was reminded how verbose $input->getOption('force') seems compared to declaring it with an attribute.

I figured it'd be a Symfony 8 thing, but it'd be great if it could arrive earlier, even if experimental.

@kaluzki
Copy link

kaluzki commented Jan 3, 2025

I’ve concerns about supporting #[AsCommand] on public methods and allowing multiple commands on the same class/instance:

  • when extending from the Command class, methods like isEnabled(), interact(), or initialize() will respond to all commands defined in that class, which is undesirable
  • when not extending from the Command class, there is currently no way to inspect methods with the #[AsCommand] attribute unless we also repeat #[AsCommand] on the class itself (for autoconfiguration/tagging)
  • last but not least, it won’t align with the SRP

I don't think it's a good idea to support that

Can't the behavior of the Command::isEnabled method be achieved directly using:

#[When(...)]
#[AsCommand(...)]

?

@yceruto yceruto force-pushed the simpler_command branch 2 times, most recently from 156e18b to 07c281f Compare January 8, 2025 16:20
@yceruto
Copy link
Member Author

yceruto commented Jan 8, 2025

Update! Added two deprecations noticies:

  • untyped parameter bound to the setCode's callable is deprecated and will throw an exception in 8.0
  • returning a non-integer value from the setCode's callable is deprecated and will throw an exception in 8.0 (it's still possible to return void)

@yceruto yceruto force-pushed the simpler_command branch 3 times, most recently from 114a39f to 82034ee Compare January 9, 2025 13:31
@@ -164,6 +164,9 @@ public function isEnabled(): bool
*/
protected function configure()
{
if (!$this->code && \is_callable($this)) {
$this->code = new InvokableCommand($this, $this(...));
Copy link
Member

@GromNaN GromNaN Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The psalm errors seems incorrect. It can be added to the baseline.

Error: src/Symfony/Component/Console/Command/Command.php:168:13: InvalidPropertyAssignment: $this with non-object type 'never' cannot treated as an object (see https://psalm.dev/010)
Error: src/Symfony/Component/Console/Command/Command.php:168:48: NoValue: All possible types for this argument were invalidated - This may be dead code (see https://psalm.dev/179)
Error: src/Symfony/Component/Console/Command/Command.php:168:55: InvalidFunctionCall: Cannot treat type never as callable (see https://psalm.dev/064)

@chalasr
Copy link
Member

chalasr commented Jan 10, 2025

Thank you @yceruto.

@chalasr chalasr merged commit 8f6560c into symfony:7.3 Jan 10, 2025
9 of 11 checks passed
@yceruto yceruto deleted the simpler_command branch January 10, 2025 12:52
chalasr added a commit that referenced this pull request Jan 11, 2025
This PR was squashed before being merged into the 7.3 branch.

Discussion
----------

[Console] Invokable command deprecations

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | yes
| Issues        | -
| License       | MIT

I believe we missed the last commit during the squash and merge of #59340. It has been applied here, along with the UPGRADE entry.

Commits
-------

71d0be1 [Console] Invokable command deprecations
Copy link
Member

@nicolas-grekas nicolas-grekas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice :) here is a late review for minor things

@@ -164,6 +164,9 @@ public function isEnabled(): bool
*/
protected function configure()
{
if (!$this->code && \is_callable($this)) {
$this->code = new InvokableCommand($this, $this(...));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This downside of this is we're now creating a self-referencing class. Might not be an issue in practice since we won't create several instances of the command object, but still worth to have in mind and prevent writing such code in the generic case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completely agree here! I'm wondering if there is an alternative solution for this case…

chalasr added a commit that referenced this pull request Jan 20, 2025
This PR was squashed before being merged into the 7.3 branch.

Discussion
----------

[Console] Invokable command adjustments

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Issues        | -
| License       | MIT

Adjustments based on the latest reviews from #59340

Commits
-------

8ab2f32 [Console] Invokable command adjustments
symfony-splitter pushed a commit to symfony/framework-bundle that referenced this pull request Jan 20, 2025
This PR was squashed before being merged into the 7.3 branch.

Discussion
----------

[Console] Invokable command adjustments

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Issues        | -
| License       | MIT

Adjustments based on the latest reviews from symfony/symfony#59340

Commits
-------

8ab2f32ba2c [Console] Invokable command adjustments
chalasr added a commit that referenced this pull request Jan 20, 2025
…ition (yceruto)

This PR was squashed before being merged into the 7.3 branch.

Discussion
----------

[Console] Add broader support for command "help" definition

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Issues        | -
| License       | MIT

Follow up #59340

Invokable and regular commands can now define the command `help` content via the `#[AsCommand]` attribute.

This is particularly useful for invokable commands, as it avoids the need to extend the `Command` class.
```php
#[AsCommand(
    name: 'user:create',
    description: 'Create a new user',
    help: <<<TXT
The <info>%command.name%</info> command generates a new user class for security
and updates your security.yaml file for it. It will also generate a user provider
class if your situation needs a custom class.

<info>php %command.full_name% email</info>

If the argument is missing, the command will ask for the class name interactively.
TXT
)]
class CreateUserCommand
{
    public function __invoke(SymfonyStyle $io, #[Argument] string $email): int
    {
        // ...
    }
}
```

Cheers!

Commits
-------

e9a6b0a [Console] Add broader support for command "help" definition
fabpot added a commit that referenced this pull request Mar 14, 2025
This PR was merged into the 7.3 branch.

Discussion
----------

[Console] Fixed support for Kernel as command

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Issues        | -
| License       | MIT

Currently, registering the Kernel as a command (see the example here: #59340 (comment)) results in an error:
```
Undefined array key "kernel"
```
I added the test case that highlights the issue and the fix (adding the `'container.no_preload'` tag to the invokable service is incorrect, as it is not the command service).

Commits
-------

c9ef38c Fixed support for Kernel as command
fabpot added a commit that referenced this pull request Mar 29, 2025
…\Closure` function set via `Command::setCode()` (yceruto)

This PR was merged into the 7.3 branch.

Discussion
----------

[Console] Deprecate returning a non-int value from a `\Closure` function set via `Command::setCode()`

| Q             | A
| ------------- | ---
| Branch?       | 7.3
| Bug fix?      | no
| New feature?  | no
| Deprecations? | yes
| Issues        | -
| License       | MIT

This adds a missing log entry about a deprecation introduced [here](#59340), and also deprecates returning a `null` value for `\Closure` code (which was allowed before) and throwing a `\TypeError` for the new invokable command, making this consistent with the `Command::execute(): int` method.

Commits
-------

787d60a Deprecate returning a non-integer value from a `\Closure` function set via `Command::setCode()`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Console DX DX = Developer eXperience (anything that improves the experience of using Symfony) Feature Status: Reviewed
Projects
None yet
Development

Successfully merging this pull request may close these issues.