@@ -817,44 +817,18 @@ loss, enable the compiler pass in your application.
817
817
Public Versus Private Services
818
818
------------------------------
819
819
820
- From Symfony 4.0, every service defined is private by default.
820
+ Every service defined is private by default. When a service is private,
821
+ you cannot accees it directly from the container object (using
822
+ ``$container->get() ``). As a best practice, you should only create
823
+ *private * services, which will happen automatically. And also, you should
824
+ *not * use the ``$container->get() `` method to fetch services, but instead
825
+ use dependency injection.
821
826
822
- What does this mean? When a service **is ** public, you can access it directly
823
- from the container object, which can also be injected thanks to autowiring.
824
- This is mostly useful when you want to fetch services lazily::
827
+ If you need to fetch services lazily, instead of using public services you
828
+ should consider using a :ref: `service locator <service-locators >` instead.
825
829
826
- namespace App\Generator;
827
-
828
- use Psr\Container\ContainerInterface;
829
-
830
- class MessageGenerator
831
- {
832
- private $container;
833
-
834
- public function __construct(ContainerInterface $container)
835
- {
836
- $this->container = $container;
837
- }
838
-
839
- public function generate(string $message, string $template = null, array $context = []): string
840
- {
841
- if ($template && $this->container->has('twig')) {
842
- // there IS a public "twig" service in the container
843
- $twig = $this->container->get('twig');
844
-
845
- return $twig->render($template, $context + ['message' => $message]);
846
- }
847
-
848
- // if no template is passed, the "twig" service will not be loaded
849
-
850
- // ...
851
- }
852
-
853
- As a best practice, you should only create *private * services, which will happen
854
- automatically. And also, you should *not * use the ``$container->get() `` method to
855
- fetch public services.
856
-
857
- But, if you *do * need to make a service public, override the ``public `` setting:
830
+ But, if you *do * need to make a service public, override the ``public ``
831
+ setting:
858
832
859
833
.. configuration-block ::
860
834
@@ -901,10 +875,10 @@ But, if you *do* need to make a service public, override the ``public`` setting:
901
875
;
902
876
};
903
877
904
- .. note ::
878
+ .. deprecated :: 5.1
905
879
906
- Instead of injecting the container you should consider using a
907
- :ref: ` service locator < service-locators >` instead .
880
+ As of Symfony 5.1, it is no longer possible to autowire the service
881
+ container by type-hinting `` Psr\Container\ContainerInterface `` .
908
882
909
883
.. _service-psr4-loader :
910
884
0 commit comments