Last active
August 24, 2021 08:25
-
-
Save winarcooo/99b600f002d640f32ec198d32d25e3a3 to your computer and use it in GitHub Desktop.
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 | |
require_once 'Container.php'; | |
class UserController | |
{ | |
public $repository; | |
public function __construct(Repository $repository) | |
{ | |
$this->repository = $repository; | |
} | |
public function getUser() | |
{ | |
echo "Controller loaded...\n"; | |
} | |
} | |
class Db | |
{ | |
public function __construct() | |
{ | |
echo "Db loaded...\n"; | |
} | |
} | |
class Model | |
{ | |
public function __construct( | |
Config $config, | |
Cache $cache | |
) { | |
$this->index(); | |
} | |
public function index() | |
{ | |
echo "Model loaded...\n"; | |
} | |
} | |
class Repository | |
{ | |
public $model; | |
public function __construct(Model $model, Env $env) | |
{ | |
$this->model = $model; | |
$this->index(); | |
} | |
public function index() | |
{ | |
echo "Repository loaded...\n"; | |
} | |
} | |
class Config | |
{ | |
public function __construct(Env $env) | |
{ | |
echo "Config loaded...\n"; | |
} | |
} | |
class Env | |
{ | |
public function __construct() | |
{ | |
echo "Env loaded...\n"; | |
} | |
} | |
class Cache | |
{ | |
public function __construct() | |
{ | |
echo "Cache loaded...\n"; | |
} | |
} | |
// create new container object | |
$container = new Container(); | |
// get userController object and resolve all dependency | |
$user = $container->resolve('UserController'); | |
$user->getUser(); |
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 | |
class Container | |
{ | |
/** | |
* * Instantiate a concrete instance of the given type. | |
*/ | |
public function resolve($concrete) | |
{ | |
$reflector = new ReflectionClass($concrete); | |
$constructor = $reflector->getConstructor(); | |
$dependencies = $constructor->getParameters(); | |
$instances = $this->getDependencies($dependencies); | |
return $reflector->newInstanceArgs($instances); | |
} | |
/** | |
* Resolve the given type from the container. | |
*/ | |
public function getDependencies($parameters = []) | |
{ | |
$results = []; | |
foreach ($parameters as $parameter) { | |
$isClass = $parameter->getClass(); | |
if ($isClass) { | |
$concrete = $parameter->name; | |
$results[] = $this->resolve($concrete); | |
} else { | |
$results[] = $parameter->getDefaultValue(); | |
} | |
} | |
return $results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment