An attempt to understand Laravel's implementation of the automated dependency resolution
. By replicating this functionality based on the tutorial from Dayle Rees.
An dependency resolution inversion of control container manages the creation of services in an application. Thereby it creates services just in the moment of request. In contrast, to creating all available services when they are registered, i.e start of the application.
We are going to build the features of the dependency resolution IoC container step by step:
- build a container class
- add an
instance()
function that stores services - add a
make()
function that retrieves services
- add a
bind()
function that acceptsclosures
to bind services - update the
make()
function that it retrievesinstances
andbindings
- cache services as an
instances
once requested (singelton-concept)
- update the
make()
function with aclass_exists()
functionality - refactor
bind()
function by extracting the dependency resolution into aautoResolve()
function - add recursive dependency resolution functionality
This tutorial makes use of the following concepts.
Services are created when they are needed. In contrast to when they are registered.
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 resolution
tries to instantiate those dependency classes. - Classes that need
integer
constructor parameters can not be instantiated through dependency resolution.
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 -> ./vendor/bin/phpunit
.