Summary - Reflection
Build a simple DI container with ReflectionClass, ReflectionMethod and attributes.
Summary - A simple DI container
To build a simple dependency container we combine every reflection tool. ReflectionClass opens the class, getConstructor() finds the constructor, getParameters() lists the dependencies.
For each parameter you instantiate the matching class and pass it via newInstanceArgs(). Attributes like #[Inject] mark which parameter is resolved automatically.
By the end of this lesson Container::make("Logger") will return a ready-made object.
Exercise Build a Logger via Container::make
The Container::make skeleton is given. Inspect $class with ReflectionClass, fetch the constructor via getConstructor(); if it is null return new $class. Otherwise build the instance with newInstanceArgs([]) and return it.
Show example solution
Build $rc = new ReflectionClass($class);. Fetch $ctor = $rc->getConstructor();. Finish with if ($ctor === null) { return new $class; } return $rc->newInstanceArgs([]);.
Example solution:
<?php
class Logger {
public function __construct(public string $name = "app") {}
}
class Container {
public static function make(string $class): object {
$rc = new ReflectionClass($class);
$ctor = $rc->getConstructor();
if ($ctor === null) {
return new $class;
}
return $rc->newInstanceArgs([]);
}
}
$logger = Container::make("Logger");
echo $logger->name . "\n";
Test yourself
-
What does a container use to resolve dependencies?
- Only getName()
- getMethods() and getProperties()
- getConstructor() and getParameters()
- Only getShortName()
Show answer
getConstructor() and getParameters() — Correct. The constructor and its parameters drive the resolution.
-
Complete the getConstructor call
<?php $rc = new ReflectionClass($class); $ctor = $rc->____(); if ($ctor === null) { return new $class; }Show answer
<?php $rc = new ReflectionClass($class); $ctor = $rc->getConstructor(); if ($ctor === null) { return new $class; } -
Match the container pieces
- getConstructor
- Finds the constructor
- getParameters
- Returns constructor parameters
- newInstanceArgs
- Builds the instance with arguments
- #[Inject]
- Dependency marker