@@ -96,69 +96,6 @@ service container. In other words, you have access to any configured service::
9696 // ...
9797 }
9898
99- However, due to the :doc: `container scopes </cookbook/service_container/scopes >` this
100- code doesn't work for some services. For instance, if you try to get the ``request ``
101- service or any other service related to it, you'll get the following error:
102-
103- .. code-block :: text
104-
105- You cannot create a service ("request") of an inactive scope ("request").
106-
107- Consider the following example that uses the ``translator `` service to
108- translate some contents using a console command::
109-
110- protected function execute(InputInterface $input, OutputInterface $output)
111- {
112- $name = $input->getArgument('name');
113- $translator = $this->getContainer()->get('translator');
114- if ($name) {
115- $output->writeln(
116- $translator->trans('Hello %name%!', array('%name%' => $name))
117- );
118- } else {
119- $output->writeln($translator->trans('Hello!'));
120- }
121- }
122-
123- If you dig into the Translator component classes, you'll see that the ``request ``
124- service is required to get the locale into which the contents are translated::
125-
126- // vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php
127- public function getLocale()
128- {
129- if (null === $this->locale && $this->container->isScopeActive('request')
130- && $this->container->has('request')) {
131- $this->locale = $this->container->get('request')->getLocale();
132- }
133-
134- return $this->locale;
135- }
136-
137- Therefore, when using the ``translator `` service inside a command, you'll get the
138- previous *"You cannot create a service of an inactive scope" * error message.
139- The solution in this case is as easy as setting the locale value explicitly
140- before translating contents::
141-
142- protected function execute(InputInterface $input, OutputInterface $output)
143- {
144- $name = $input->getArgument('name');
145- $locale = $input->getArgument('locale');
146-
147- $translator = $this->getContainer()->get('translator');
148- $translator->setLocale($locale);
149-
150- if ($name) {
151- $output->writeln(
152- $translator->trans('Hello %name%!', array('%name%' => $name))
153- );
154- } else {
155- $output->writeln($translator->trans('Hello!'));
156- }
157- }
158-
159- However, for other services the solution might be more complex. For more details,
160- see :doc: `/cookbook/service_container/scopes `.
161-
16299Invoking other Commands
163100-----------------------
164101
0 commit comments