From 2def992aeaf2851d32e46d4cd85945568b973703 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 21 Nov 2017 09:27:43 -0500 Subject: [PATCH 1/2] Rewriting logic for accessing services from the console --- console.rst | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/console.rst b/console.rst index 8227269a07c..bf1625c7eab 100644 --- a/console.rst +++ b/console.rst @@ -169,33 +169,34 @@ Getting Services from the Service Container ------------------------------------------- To actually create a new user, the command has to access to some -:doc:`services `. This can be done by making the command -extend the :class:`Symfony\\Bundle\\FrameworkBundle\\Command\\ContainerAwareCommand` -instead:: +:doc:`services `. Since your command is already registered +as a service, you can use normal dependency injection. Imagine you have a +``AppBundle\Service\UserManager`` service that you want to access:: // ... - use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; + use AppBundle\Service\UserManager; class CreateUserCommand extends ContainerAwareCommand { + private $userManager; + + public function __construct(UserManager $userManager) + { + $this->userManager = $userManager; + } + // ... protected function execute(InputInterface $input, OutputInterface $output) { // ... - // access the container using getContainer() - $userManager = $this->getContainer()->get('app.user_manager'); - $userManager->create($input->getArgument('username')); + $this->userManager->create($input->getArgument('username')); $output->writeln('User successfully generated!'); } } -Now, once you have created the required services and logic, the command will execute -the ``create()`` method of the ``app.user_manager`` service and the user will -be created. - Command Lifecycle ----------------- From 4f656f266845c764a13dd2c0359b552ade76fbaf Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Tue, 21 Nov 2017 14:06:01 -0500 Subject: [PATCH 2/2] fixing bad class --- console.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/console.rst b/console.rst index bf1625c7eab..9ddd9f83aa9 100644 --- a/console.rst +++ b/console.rst @@ -174,9 +174,10 @@ as a service, you can use normal dependency injection. Imagine you have a ``AppBundle\Service\UserManager`` service that you want to access:: // ... + use Symfony\Component\Console\Command\Command; use AppBundle\Service\UserManager; - class CreateUserCommand extends ContainerAwareCommand + class CreateUserCommand extends Command { private $userManager;