Skip to content

Instantly share code, notes, and snippets.

@vihugarcia
Created July 26, 2023 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vihugarcia/29b03203990afe92f3d3f5ae5e98bdbb to your computer and use it in GitHub Desktop.
Save vihugarcia/29b03203990afe92f3d3f5ae5e98bdbb to your computer and use it in GitHub Desktop.
Chapter 09 DependencyResolver.php
<?php
namespace SimpleMVC\core;
class DependencyResolver {
private static $map = [];
public static function set($key, $value) {
if (!array_key_exists($key, self::$map)) {
self::$map[$key] = $value;
}
}
public static function resolveDependencies($class) {
$reflector = new \ReflectionClass($class);
$method = $reflector->getConstructor();
$parameters = $method->getParameters();
$dependencies = [];
foreach ($parameters as $parameter) {
$parameterType = $parameter->getType();
if ($parameterType === null || $parameterType->isBuiltin()) {
$parameterName = $parameter->getName();
// Handling non classes parameters
if (array_key_exists($parameterName, self::$map)) {
$dependencies[] = self::$map[$parameterName];
}
} else {
$dependencyClassName = $parameterType->getName();
$dependencies[] = self::resolveDependencies($dependencyClassName);
}
}
return $reflector->newInstanceArgs($dependencies);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment