In this article, we will see some examples of using Symfony Dependency Injection Component. You’ll learn the basics of Dependency Injection, which allows for cleaner and more modular code, and you’ll see how to use it in your PHP application with Symfony Component.
What is Symfony Dependency Injection Component?
Symfony Dependency Injection Component provides a standard way to instantiate objects in your PHP applications and to handle the Dependency Manager. The heart of the dependency injection component is a container that holds all available services in the application.
During the bootstrapping step of your application, you have to register all the services in your application in the container. In the latter step, the container is responsible for creating the services as required. Most importantly, the Container is also responsible for creating and injecting the services’ dependencies.
The advantage of this approach is that you do not need to make the process of creating objects hard because the dependencies will be detected and injected automatically. This creates a loose coupling between parts of your application.
In this article, we will explore how you can release the power of the dependency injection component. As usual, we will start with installation and configuration instructions, and we will implement some real-world examples to demonstrate key concepts.
Installations and Configurations
In this section, we will go ahead and install the Dependency Injection Component. I think you have already installed Composer in your system as we will need it to install the dependency injection component available on Packagist.
How to work with container
In this section, we will look through an example to show how you can inject services into a container. A container should act as a central repository that holds all the services in your application. Later, we could use containers to fetch services as needed.
To get started, go ahead and define a beautiful basic service on src / DemoService.php with the following content.
A real-world example of Symfony
In this section, we will create an example that shows how class dependency is resolved using the Dependency Injection Component.
To demonstrate this, we will provide a new service DependentService that requires the DemoService service created in the previous section as Dependency. Thus, we will see that the DemoService service is injected automatically as a dependency when the DependentServcie service starts.
Go ahead and create an src / DependentService.php file with the following content to define the DependentService service.