Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
chalasr merged 1 commit intosymfony:7.3fromyceruto:simpler_command
Jan 10, 2025

Conversation

yceruto
Copy link
Member

@ycerutoyceruto commentedDec 31, 2024
edited
Loading

QA
Branch?7.3
Bug fix?no
New feature?yes
Deprecations?yes
Issues-
LicenseMIT

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 theCommand 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 to0 (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 viaCommand::setCode() #60076 .

Before

#[AsCommand(name:'lucky:number')]class LuckyNumberCommandextends Command{publicfunction__construct(privateLuckyNumberGenerator$generator)    {parent::__construct();    }protectedfunctionconfigure():void    {$this->addArgument('name', InputArgument::REQUIRED);$this->addOption('formal',null, InputOption::VALUE_NONE | InputOption::VALUE_NEGATABLE);    }publicfunctionexecute(InputInterface$input,OutputInterface$output):int    {$io =newSymfonyStyle($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()));return0;    }}

After

#[AsCommand(name:'lucky:number')]class LuckyNumberCommand{publicfunction__construct(privateLuckyNumberGenerator$generator)    {    }publicfunction__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()));return0;    }}

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

Happy New Year! 🎉

jvasseur, Fan2Shrek, seferov, and yceruto reacted with thumbs up emojiwelcoMattic, emnsen, seferov, yceruto, and wkania reacted with hooray emojikbond, ging-dev, pmtpro, Kocal, smnandre, Koc, kaluzki, Jean-Beru, chalasr, alamirault, and 18 more reacted with heart emojiOskarStark, ging-dev, kaluzki, Jean-Beru, 94noni, chalasr, welcoMattic, WebMamba, mtarld, Fan2Shrek, and 5 more reacted with rocket emoji
@carsonbotcarsonbot added Status: Needs Review Console DXDX = Developer eXperience (anything that improves the experience of using Symfony) Feature labelsDec 31, 2024
@carsonbotcarsonbot added this to the7.3 milestoneDec 31, 2024
@carsonbotcarsonbot changed the title[Console][DX] Add support for invokable commands and input attributes[Console] Add support for invokable commands and input attributesDec 31, 2024
@ycerutoyceruto requested a review fromkbondDecember 31, 2024 19:28
Copy link
Member

@kbondkbond 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!

GromNaN, smnandre, and kaluzki reacted with thumbs up emoji
Copy link
Member

@GromNaNGromNaN 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 theAsCommand 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 adebug:console command to find the callable associated to each command.

rvanlaak reacted with eyes emoji
@94noni
Copy link
Contributor

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
MemberAuthor

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

OskarStark and chalasr reacted with heart emoji

@ycerutoycerutoforce-pushed thesimpler_command branch 3 times, most recently fromd8a8a6d toaafa900CompareJanuary 1, 2025 20:02
@yceruto
Copy link
MemberAuthor

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

<?phprequire_once__DIR__.'/vendor/autoload_runtime.php';useSymfony\Bundle\FrameworkBundle\Console\Application;useSymfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;useSymfony\Component\Console\Attribute\Argument;useSymfony\Component\Console\Attribute\AsCommand;useSymfony\Component\Console\Style\SymfonyStyle;useSymfony\Component\HttpKernel\Kernel;#[AsCommand('app:start')]class SymfonyOneFileAppextends Kernel{use MicroKernelTrait;publicfunction__invoke(SymfonyStyle$io, #[Argument]string$name ='World'):void    {$io->success(sprintf('Hello %s!',$name));    }}returnstaticfunction (array$context) {returnnewApplication(newSymfonyOneFileApp($context['APP_ENV'], (bool)$context['APP_DEBUG']));};

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

@yceruto
Copy link
MemberAuthor

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.

94noni reacted with thumbs up emoji

@smnandre
Copy link
Member

I love it! Really nice DX addition 👏

yceruto reacted with rocket emoji

@yceruto
Copy link
MemberAuthor

yceruto commentedJan 2, 2025
edited
Loading

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

  • when extending from theCommand class, methods likeisEnabled(),interact(), orinitialize() will respond to all commands defined in that class, which is undesirable
  • when not extending from theCommand 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

OskarStark, chalasr, dunglas, and rvanlaak reacted with thumbs up emoji


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
MemberAuthor

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 orcallable in the attribute constructor. Allowing this suggestion methods to access the instance's dependencies.

Copy link
MemberAuthor

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'])] wheregetPermissions 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)

chalasr and GromNaN reacted with thumbs up emoji
@GromNaN
Copy link
Member

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

  • when extending from theCommand class, methods likeisEnabled(),interact(), orinitialize() 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 theCommand 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:

TheregisterAttributeForAutoconfiguration 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.

kaluzki reacted with thumbs up emoji

@yceruto
Copy link
MemberAuthor

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 theinteract() 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.

OskarStark reacted with thumbs up emoji

@ycerutoycerutoforce-pushed thesimpler_command branch 2 times, most recently from9873de3 to14e8332CompareJanuary 2, 2025 15:03
@tacman
Copy link
Contributor

Woo hoo! I lovehttps://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

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

  • when extending from theCommand class, methods likeisEnabled(),interact(), orinitialize() will respond to all commands defined in that class, which is undesirable
  • when not extending from theCommand 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 theCommand::isEnabled method be achieved directly using:

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

?

@@ -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

@GromNaNGromNaNJan 9, 2025
edited
Loading

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

Thank you@yceruto.

yceruto reacted with hooray emoji

@chalasrchalasr merged commit8f6560c intosymfony:7.3Jan 10, 2025
9 of 11 checks passed
@ycerutoyceruto deleted the simpler_command branchJanuary 10, 2025 12:52
chalasr added a commit that referenced this pull requestJan 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       | MITI 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-grekasnicolas-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

chalasr and yceruto reacted with thumbs up emoji
@@ -164,6 +164,9 @@ public function isEnabled(): bool
*/
protectedfunctionconfigure()
{
if (!$this->code &&\is_callable($this)) {
$this->code =newInvokableCommand($this,$this(...));

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
MemberAuthor

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 requestJan 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       | MITAdjustments based on the latest reviews from#59340Commits-------8ab2f32 [Console] Invokable command adjustments
symfony-splitter pushed a commit to symfony/framework-bundle that referenced this pull requestJan 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       | MITAdjustments based on the latest reviews fromsymfony/symfony#59340Commits-------8ab2f32ba2c [Console] Invokable command adjustments
chalasr added a commit that referenced this pull requestJan 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       | MITFollow up#59340Invokable 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: <<<TXTThe <info>%command.name%</info> command generates a new user class for securityand updates your security.yaml file for it. It will also generate a user providerclass 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 requestMar 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       | MITCurrently, 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 requestMar 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       | MITThis 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()`
@fabpotfabpot mentioned this pull requestMay 2, 2025
@BafS
Copy link
Contributor

I love this feature, congrats! But it's pretty hard to customize the parameters match inInvokableCommand, for example to inject a customOutputStyle we need to override a lot of logic because there is no injection ofInvokableCommand and the match is in a private method.

The obvious workaround is to injectInputInterface $input, OutputInterface $output and build the custom style.

How do you see it? Is it something we could improve?

@OskarStark
Copy link
Contributor

Please create a new issue, thanks

BafS reacted with thumbs up emoji

@chalasr
Copy link
Member

chalasr commentedMay 30, 2025
edited
Loading

I will resume#59794 for 7.4 - main goal is to provide an extension point for such use cases.

BafS reacted with heart emoji

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@fabpotfabpotfabpot requested changes

@nicolas-grekasnicolas-grekasnicolas-grekas left review comments

@stofstofstof left review comments

@theofidrytheofidrytheofidry approved these changes

@chalasrchalasrchalasr approved these changes

@kbondkbondkbond approved these changes

@GromNaNGromNaNGromNaN approved these changes

@OskarStarkOskarStarkOskarStark approved these changes

@mtarldmtarldmtarld approved these changes

Assignees
No one assigned
Labels
ConsoleDXDX = Developer eXperience (anything that improves the experience of using Symfony)FeatureStatus: Reviewed
Projects
None yet
Milestone
7.3
Development

Successfully merging this pull request may close these issues.

17 participants
@yceruto@94noni@OskarStark@smnandre@GromNaN@tacman@kaluzki@chalasr@alamirault@BafS@fabpot@kbond@nicolas-grekas@stof@mtarld@theofidry@carsonbot

[8]ページ先頭

©2009-2025 Movatter.jp