File tree Expand file tree Collapse file tree 3 files changed +49
-0
lines changed
cookbook/service_container Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -4,5 +4,6 @@ Service Container
44.. toctree ::
55 :maxdepth: 2
66
7+ shared
78 scopes
89 compiler_passes
Original file line number Diff line number Diff line change @@ -8,6 +8,11 @@ How to Work with Scopes
88
99 The "container scopes" concept explained in this article has been deprecated
1010 in Symfony 2.8 and it will be removed in Symfony 3.0.
11+
12+ Use the ``request_stack `` service (introduced in Symfony 2.4) instead of
13+ the ``request `` service/scope and use the ``shared `` setting (introduced in
14+ Symfony 2.8) instead of the ``prototype `` scope
15+ (:doc: `read more about shared services </cookbook/service_container/shared >`).
1116
1217This article is all about scopes, a somewhat advanced topic related to the
1318:doc: `/book/service_container `. If you've ever gotten an error mentioning
Original file line number Diff line number Diff line change 1+ .. index ::
2+ single: Service Container; Shared Services
3+
4+ How to Define Not Shared Services
5+ =================================
6+
7+ .. versionadded :: 2.8
8+ The ``shared `` setting was introduced in Symfony 2.8. Prior to Symfony 2.8,
9+ you had to use the ``prototype `` scope.
10+
11+ In the service container, all services are shared by default. This means that
12+ each time you retrieve the service, you'll get the *same * instance. This is
13+ often the behaviour you want, but in some cases, you might want to always get a
14+ *new * instance.
15+
16+ In order to always get a new instance, set the ``shared `` setting to ``false ``
17+ in your service definition:
18+
19+ .. configuration-block ::
20+
21+ .. code-block :: yaml
22+
23+ services :
24+ app.some_not_shared_service :
25+ class : ...
26+ shared : false
27+ # ...
28+
29+ .. code-block :: xml
30+
31+ <services >
32+ <service id =" app.some_not_shared_service" class =" ..." shared =" false" />
33+ </services >
34+
35+ .. code-block :: php
36+
37+ $definition = new Definition('...');
38+ $definition->setShared(false);
39+
40+ $container->setDefinition('app.some_not_shared_service', $definition);
41+
42+ Now, whenever you call ``$container->get('app.some_not_shared_service') `` or
43+ inject this service, you'll recieve a new instance.
You can’t perform that action at this time.
0 commit comments