Symfony Services and Dependency Injection


Now that you've seen how Symfony Services are created, and how we can inject parameters into those Services, it's time to make things a little more interesting by looking at how we can use Dependency Injection to create Symfony Services that contain other Services.

Dependency Injection is one of those scary sounding topics that may be stopping you from pursuing Symfony, or any other modern PHP MVC framework. Let me reassure you, whilst it might sound scary, it is a really simple concept to grasp, especially once you've seen it in action.

All we are trying to do here is make our lives easier. Think of each of our Symfony Services as an individual lego brick. Lets say we have a LegoHead service, a LegoBody service, and a LegoLegs service.

We want to create ourselves a little yellow Lego person.

Perhaps we would create a new LegoPerson service and pass in (or Inject) our LegoHead, LegoBody, and LegoLegs services (dependencies).

Pretty simple, no? If our component / Service needs other components / Services to work properly, we simply want to make sure they are all present and correct. We do this by passing them in, or Injecting them.

Remember, at the heart of any Service inside Symfony, is a simple PHP Class. Nothing more. That class may be simple - a standalone class with no extras required, or it may be complex - requiring lots of other classes to function properly. From Symfony's perspective, we still define those Services in exactly the same way.

In this video we're going to look at how a Service can depend on one or more other Services. Those Dependencies are managed by the configuration we supply in our services.yml file. We already know how to inject parameters using the % symbol, and injecting other Services is almost entirely the same, only this time we use the @ symbol instead.

The main thing to remember really is to ensure any arguments we add in to our services.yml file are met with a corresponding entry in our PHP Class's __construct() method.

Code For This Video

Get the code for this video.

Episodes

# Title Duration
1 Symfony Services 101 06:27
2 Symfony Services and Dependency Injection 05:13
3 Symfony Services in the Real World 09:49
4 Dependency Injection and Symfony Services (Updated for 3.3) 08:33