Last active
March 21, 2019 09:30
-
-
Save kanian/0bd6f0bfc10a5425e1a1529420560a1a to your computer and use it in GitHub Desktop.
Sample Code for Container Resolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Kanian\ContainerX; | |
use Kanian\ContainerX\Exceptions\DependencyHasNoDefaultValueException; | |
use Kanian\ContainerX\Exceptions\DependencyIsNotInstantiableException; | |
use Psr\Container\ContainerInterface; | |
use ReflectionClass; | |
use ReflectionException; | |
use ReflectionParameter; | |
/** | |
* A psr-11 compliant container | |
*/ | |
class Container implements ContainerInterface | |
{ | |
//... | |
public function concretize(string $entry) | |
{ | |
$resolved = []; | |
$reflector = $this->getReflector($entry); | |
$constructor = null; | |
$parameters = []; | |
if ($reflector->isInstantiable()) { | |
$constructor = $reflector->getConstructor(); | |
if (!is_null($constructor)) { | |
$parameters = $constructor->getParameters(); | |
} | |
} else { | |
throw new DependencyIsNotInstantiableException($className); | |
} | |
if (is_null($constructor) || empty($parameters)) { | |
return $reflector->newInstance(); // return new instance from class | |
} | |
foreach ($parameters as $parameter) { | |
$resolved[] = $this->resolveParameter($parameter); | |
} | |
return $reflector->newInstanceArgs($resolved); // return new instance with dependencies resolved | |
} | |
public function resolveParameter(ReflectionParameter $parameter) | |
{ | |
if ($parameter->getClass() !== null) { // The parameter is a class | |
$typeName = $parameter->getType()->__toString(); | |
if (!$this->isUserDefined($parameter)) { // The parameter is not user defined | |
$this->set($typeName); // Register it | |
} | |
return $this->get($typeName); // Instantiate it | |
} else { // The parameter is a built-in primitive type | |
if ($parameter->isDefaultValueAvailable()) { // Check if default value for a parameter is available | |
return $parameter->getDefaultValue(); // Get default value of parameter | |
} else { | |
throw new DependencyHasNoDefaultValueException($parameter->name); | |
} | |
} | |
} | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment