Skip to content

Commit 947ad92

Browse files
author
Loïc Chardonnet
committed
[Console] Adding use cases to command as service
| Q | A | ------------- | --- | Doc fix? | yes | New docs? | no | Applies to | 2.4+ | Fixed tickets | N/A Command as a service can be useful to give access to services and configuration parameters in the `configure` method. A simple use case: you want to allow the user to set an option's default value in the `app/config/parameters.yml` file. Or the default value needs to be computed by a service (database retrieval for instance). With a `ContainerAwareCommand`, this wouldn't be possible because the `configure` method is called from the constructor, so the container isn't set yet.
1 parent 5c4336a commit 947ad92

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

cookbook/console/console_command.rst

+20-6
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,12 @@ Register Commands in the Service Container
7171
Support for registering commands in the service container was added in
7272
version 2.4.
7373

74-
Instead of putting your command in the ``Command`` directory and having Symfony
75-
auto-discover it for you, you can register commands in the service container
76-
using the ``console.command`` tag:
74+
By default, Symfony will take a look in the ``Command`` directory of you
75+
bundles and automatically register your commands. For the ones implementing
76+
the ``ContainerAwareCommand`` interface, Symfony will even inject the container.
77+
78+
If you wan to, you can instead register them as services in the container using
79+
the ``console.command`` tag:
7780

7881
.. configuration-block::
7982

@@ -111,9 +114,20 @@ using the ``console.command`` tag:
111114
112115
.. tip::
113116

114-
Registering your command as a service gives you more control over its
115-
location and the services that are injected into it. But, there are no
116-
functional advantages, so you don't need to register your command as a service.
117+
Command as a service can be usefull in few situations:
118+
* if you need your commands to be defined somewhere else than ``Command``
119+
* if you need to access services or configuration parameters in the
120+
``configure`` method
121+
122+
For example, Imagine you want to provide a default value for the ``name``
123+
option. You could hard code a string and pass it as the 4th argument of
124+
``addArgument``, or you could allow the user to set the default value in the
125+
configuration.
126+
127+
With a ``ContainerAwareCommand`` you wouldn't be able to retrieve the
128+
configuration parameter, because the ``configure`` method is called in the
129+
command's constructor. The only solution is to inject them through its
130+
constructor.
117131

118132
Getting Services from the Service Container
119133
-------------------------------------------

0 commit comments

Comments
 (0)