From 10f30b41c2c72f14947a7ef0d8be8cbc3f2f679e Mon Sep 17 00:00:00 2001 From: WouterJ Date: Wed, 24 Jun 2015 22:57:04 +0200 Subject: [PATCH] Added minimal cookbook article about shared --- cookbook/service_container/index.rst | 1 + cookbook/service_container/scopes.rst | 5 ++++ cookbook/service_container/shared.rst | 43 +++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 cookbook/service_container/shared.rst diff --git a/cookbook/service_container/index.rst b/cookbook/service_container/index.rst index f66a455b788..f0166e75fd8 100644 --- a/cookbook/service_container/index.rst +++ b/cookbook/service_container/index.rst @@ -4,5 +4,6 @@ Service Container .. toctree:: :maxdepth: 2 + shared scopes compiler_passes diff --git a/cookbook/service_container/scopes.rst b/cookbook/service_container/scopes.rst index 13d35e4cc1e..50e644b12f2 100644 --- a/cookbook/service_container/scopes.rst +++ b/cookbook/service_container/scopes.rst @@ -8,6 +8,11 @@ How to Work with Scopes The "container scopes" concept explained in this article has been deprecated in Symfony 2.8 and it will be removed in Symfony 3.0. + + Use the ``request_stack`` service (introduced in Symfony 2.4) instead of + the ``request`` service/scope and use the ``shared`` setting (introduced in + Symfony 2.8) instead of the ``prototype`` scope + (:doc:`read more about shared services `). This article is all about scopes, a somewhat advanced topic related to the :doc:`/book/service_container`. If you've ever gotten an error mentioning diff --git a/cookbook/service_container/shared.rst b/cookbook/service_container/shared.rst new file mode 100644 index 00000000000..205afd7028d --- /dev/null +++ b/cookbook/service_container/shared.rst @@ -0,0 +1,43 @@ +.. index:: + single: Service Container; Shared Services + +How to Define Not Shared Services +================================= + +.. versionadded:: 2.8 + The ``shared`` setting was introduced in Symfony 2.8. Prior to Symfony 2.8, + you had to use the ``prototype`` scope. + +In the service container, all services are shared by default. This means that +each time you retrieve the service, you'll get the *same* instance. This is +often the behaviour you want, but in some cases, you might want to always get a +*new* instance. + +In order to always get a new instance, set the ``shared`` setting to ``false`` +in your service definition: + +.. configuration-block:: + + .. code-block:: yaml + + services: + app.some_not_shared_service: + class: ... + shared: false + # ... + + .. code-block:: xml + + + + + + .. code-block:: php + + $definition = new Definition('...'); + $definition->setShared(false); + + $container->setDefinition('app.some_not_shared_service', $definition); + +Now, whenever you call ``$container->get('app.some_not_shared_service')`` or +inject this service, you'll recieve a new instance.