@@ -10,6 +10,13 @@ The traditional way of adding commands to your application is to use
10
10
:method: `Symfony\\ Component\\ Console\\ Application::add `, which expects a
11
11
``Command `` instance as an argument.
12
12
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
+
13
20
In order to lazy-load commands, you need to register an intermediate loader
14
21
which will be responsible for returning ``Command `` instances::
15
22
@@ -19,7 +26,9 @@ which will be responsible for returning ``Command`` instances::
19
26
use Symfony\Component\Console\CommandLoader\FactoryCommandLoader;
20
27
21
28
$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(),
23
32
]);
24
33
25
34
$application = new Application();
@@ -36,6 +45,28 @@ method accepts any
36
45
:class: `Symfony\\ Component\\ Console\\ CommandLoader\\ CommandLoaderInterface `
37
46
instance so you can use your own implementation.
38
47
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
+
39
70
Built-in Command Loaders
40
71
------------------------
41
72
0 commit comments