Skip to content

Commit 2def992

Browse files
committed
Rewriting logic for accessing services from the console
1 parent d18ec42 commit 2def992

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

console.rst

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -169,33 +169,34 @@ Getting Services from the Service Container
169169
-------------------------------------------
170170

171171
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::
175175

176176
// ...
177-
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
177+
use AppBundle\Service\UserManager;
178178

179179
class CreateUserCommand extends ContainerAwareCommand
180180
{
181+
private $userManager;
182+
183+
public function __construct(UserManager $userManager)
184+
{
185+
$this->userManager = $userManager;
186+
}
187+
181188
// ...
182189

183190
protected function execute(InputInterface $input, OutputInterface $output)
184191
{
185192
// ...
186193

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'));
190195

191196
$output->writeln('User successfully generated!');
192197
}
193198
}
194199

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-
199200
Command Lifecycle
200201
-----------------
201202

0 commit comments

Comments
 (0)