Skip to content

Rewriting logic for accessing services from the console #8714

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 24, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions console.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 </service_container>`. This can be done by making the command
extend the :class:`Symfony\\Bundle\\FrameworkBundle\\Command\\ContainerAwareCommand`
instead::
:doc:`services </service_container>`. 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
Copy link
Member

@yceruto yceruto Nov 21, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Command + use then?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

of course! Good catch

{
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
-----------------

Expand Down