Published Feb 12, 2019 / 2 min read
Understanding dependency resolutions in PHP
An attempt to understand Laravel's implementation of the automated
dependency resolution. By replicating this functionality based on the tutorial from Dayle Rees.
Features of the IoC container
We are going to build the features of the dependency resolution IoC container step by step:
A. Build a container that stores and retrieves services
- build a container class
- add an
instance()function that stores services
- add a
make()function that retrieves services
B. Add inversion of control functionality
- add a
bind()function that accepts
closuresto bind services
- update the
make()function that it retrieves
- cache services as an
instancesonce requested (singelton-concept)
C. Add automated (recursive) dependency resolution
- update the
make()function with a
bind()function by extracting the dependency resolution into a
- add recursive dependency resolution functionality
This tutorial makes use of the following concepts.
1. Inversion of control
Services are created when they are needed. In contrast to when they are registered.
2. Dependency resolution
It is about automated creation of classes during the run time of an application.
- Classes without constructor parameter (dependencies) can be created automatically.
- Classes that need as constructor parameter another class or even multiple classes, can only be instantiated when this dependency is available. The concept of
recursive dependency resolutiontries to instantiate those dependency classes.
- Classes that need
integerconstructor parameters can not be instantiated through dependency resolution.
3. PHP reflection classes
PHP has a reflection API that enable us to reverse engineer a class and retrieve information about the nature of the class and associated interfaces, functions, extensions.
To automatically resolve classes wit construction parameters we need to make use of the reflection API to receive the dependent class instantiate them accordingly.
You will find withing the
tests directory a
containerTest.php with 6 different test cases. Run all tests with ->