New in Symfony 3.2: Improved private services

Contributed by
Hugo Hamon
in #19146.

Private services have been supported in the Symfony Service Container since day one. By default all services are public, but setting the public option to false will turn them into private services:

1
2
3
4
services:
    app.manager.user:
        class: AppBundle\Manager\User
        public: false

Intuitively, you may think that private services are no longer accessible from the container. However, their behavior is a bit tricky:

  • If a private service is not injected in any other service, it's removed from the container;
  • If a private service is only injected to one service, it's inlined and its definition is removed from the container;
  • If a private service is injected to more than one service, then it behaves like a public service and you can even get it via $container->get('...').

This last behaviour is counterintuitive, so we decided to improve private services in Symfony 3.2. From now on, a private service always behaves like you expect:

  • Setting or unsetting a private service with the Container::set() method is deprecated in Symfony 3.2 and no longer supported in 4.0;
  • Checking the existence of a private service with the Container::has() will always return false in Symfony 4.0;
  • Requesting a private service with the Container::get() method is deprecated in Symfony 3.2 and no longer returns the service in 4.0.

The next step, which may be completed before Symfony 3.2 release, will be to randomize the id of the private services, making it impossible for applications to get those services circumventing the restrictions imposed by Symfony.

Comments

Nice write up. Your first bullet points read "If a private project..." I assume "project" should be "service".
@Tony fixed! Thanks.
What is supposed to happen when you override a service declaration of a private service?

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.