Skip to content

Commit 1f867e6

Browse files
committed
minor #8714 Rewriting logic for accessing services from the console (weaverryan)
This PR was squashed before being merged into the 3.4 branch (closes #8714). Discussion ---------- Rewriting logic for accessing services from the console Fixes #8713 This is against 3.4, because it is the first time that your commands will be registered as services in practice. Commits ------- 4f656f2 fixing bad class 2def992 Rewriting logic for accessing services from the console
2 parents 215d667 + 4f656f2 commit 1f867e6

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

console.rst

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,33 +169,35 @@ 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 Symfony\Component\Console\Command\Command;
178+
use AppBundle\Service\UserManager;
178179

179-
class CreateUserCommand extends ContainerAwareCommand
180+
class CreateUserCommand extends Command
180181
{
182+
private $userManager;
183+
184+
public function __construct(UserManager $userManager)
185+
{
186+
$this->userManager = $userManager;
187+
}
188+
181189
// ...
182190

183191
protected function execute(InputInterface $input, OutputInterface $output)
184192
{
185193
// ...
186194

187-
// access the container using getContainer()
188-
$userManager = $this->getContainer()->get('app.user_manager');
189-
$userManager->create($input->getArgument('username'));
195+
$this->userManager->create($input->getArgument('username'));
190196

191197
$output->writeln('User successfully generated!');
192198
}
193199
}
194200

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-
199201
Command Lifecycle
200202
-----------------
201203

0 commit comments

Comments
 (0)