@@ -169,33 +169,34 @@ Getting Services from the Service Container
169
169
-------------------------------------------
170
170
171
171
To actually create a new user, the command has to access to some
172
- :doc: `services </service_container >`. This can be done by making the command
173
- extend the :class: ` Symfony \\ Bundle \\ FrameworkBundle \\ Command \\ ContainerAwareCommand `
174
- instead ::
172
+ :doc: `services </service_container >`. Since your command is already registered
173
+ as a service, you can use normal dependency injection. Imagine you have a
174
+ `` AppBundle\Service\UserManager `` service that you want to access ::
175
175
176
176
// ...
177
- use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand ;
177
+ use AppBundle\Service\UserManager ;
178
178
179
179
class CreateUserCommand extends ContainerAwareCommand
180
180
{
181
+ private $userManager;
182
+
183
+ public function __construct(UserManager $userManager)
184
+ {
185
+ $this->userManager = $userManager;
186
+ }
187
+
181
188
// ...
182
189
183
190
protected function execute(InputInterface $input, OutputInterface $output)
184
191
{
185
192
// ...
186
193
187
- // access the container using getContainer()
188
- $userManager = $this->getContainer()->get('app.user_manager');
189
- $userManager->create($input->getArgument('username'));
194
+ $this->userManager->create($input->getArgument('username'));
190
195
191
196
$output->writeln('User successfully generated!');
192
197
}
193
198
}
194
199
195
- Now, once you have created the required services and logic, the command will execute
196
- the ``create() `` method of the ``app.user_manager `` service and the user will
197
- be created.
198
-
199
200
Command Lifecycle
200
201
-----------------
201
202
0 commit comments