@@ -10,6 +10,13 @@ The traditional way of adding commands to your application is to use
1010:method: `Symfony\\ Component\\ Console\\ Application::add `, which expects a
1111``Command `` instance as an argument.
1212
13+ This approach can have downsides as some commands might be expensive to
14+ instantiate in which case you may want to lazy-load them. Note however that lazy-loading
15+ is not absolute. Indeed a few commands such as `list `, `help ` or `_complete ` can
16+ require to instantiate other commands although they are lazy. For example `list ` needs
17+ to get the name and description of all commands, which might require the command to be
18+ instantiated to get.
19+
1320In order to lazy-load commands, you need to register an intermediate loader
1421which will be responsible for returning ``Command `` instances::
1522
@@ -19,7 +26,9 @@ which will be responsible for returning ``Command`` instances::
1926 use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
2027
2128 $commandLoader = new FactoryCommandLoader([
22- 'app:heavy' => function (): Command { return new HeavyCommand(); },
29+ // Note that the `list` command will still instantiate that command
30+ // in this example.
31+ 'app:heavy' => static fn(): Command => new HeavyCommand(),
2332 ]);
2433
2534 $application = new Application();
@@ -36,6 +45,28 @@ method accepts any
3645:class: `Symfony\\ Component\\ Console\\ CommandLoader\\ CommandLoaderInterface `
3746instance so you can use your own implementation.
3847
48+ Another way to do so is to take advantage of ``Symfony\Component\Console\Command\LazyCommand ``::
49+
50+ use App\Command\HeavyCommand;
51+ use Symfony\Component\Console\Application;
52+ use Symfony\Component\Console\Command\Command;
53+ use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
54+
55+ // In this case although the command is instantiated, the underlying command factory
56+ // will not be executed unless the command is actually executed or one tries to access
57+ // to its input definition to know its argument or option inputs.
58+ $lazyCommand = new LazyCommand(
59+ 'app:heavy',
60+ [],
61+ 'This is another more complete form of lazy command.',
62+ false,
63+ static fn (): Command => new HeavyCommand(),
64+ );
65+
66+ $application = new Application();
67+ $application->add($lazyCommand);
68+ $application->run();
69+
3970Built-in Command Loaders
4071------------------------
4172
0 commit comments