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