Symfony2 service container

→ Are you a new visitor? Please visit the page guidance for new visitors ←


A big PHP aplication should be OOP written and should have a lot of objects. You can split them by functionality depending on what they do. Some of them are used for interaction with database, some of them are used to save information in files.This chapter is about a special PHP object in Symfony2 that helps you instantiate, organize and retrieve the many objects of your application. This object, called a service container, will allow you to standardize and centralize the way objects are constructed in your application. It is highly recomended to create containers because it promotes reusable, decoupled and fast code.


A service is a PHP class that is used to perform some global operations. Each service is used throughout your application whenever you need the specific functionality it provides.

Often called dependency injection container, it is simply a PHP object that manages the instantiation of services (i.e. objects).

Dependency injection explained

Basically, instead of having your objects creating a dependency, you pass the needed dependencies in to the constructor or via property setters of another class.  The following example is showing how a good part of developers think about good coding.

You have two classes, one for Author and one for Post. This classes need somehow to be used together as you see. In the post class we need the Author object because we have to set later some information about that in the database perhaps. This is not that good code because the Author‘s information passed to the Post constructor has nothing to do inside Post‘s scope. This code will result in hard testing.

By using dependency injection pattern, you will avoid these problems by inserting the dependencies (objects of other class) directly into the controller of the other class. This will result in more maintainable code. Let’s see how we obtain this:

This will result in better code and better testing! Now, let’s get back to Symfony’s service container.

Creating services in the container

Let’s say we have to manage views for a certain post in our application. We choose to create a service that deals with that. We will start by adding in the “app/config/config.yml” the followings:

We specify the class with the namespace, the arguments and the service itself. Now we have to creat the physical class:

We defined an “incrementViews” method that deals with the incrementations on the post views. Now inside the controller we can use this service like this:

Pretty simple, huh ?

More information about this can be found here.

Request an article ←