Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created May 8, 2019 14:38
Show Gist options
  • Save kobus1998/447faae2c123cb0cc722a1975af8f8f4 to your computer and use it in GitHub Desktop.
Save kobus1998/447faae2c123cb0cc722a1975af8f8f4 to your computer and use it in GitHub Desktop.
Autowire container with league\container
<?php
require __DIR__ . '/vendor/autoload.php';
use \App\Foo;
use \App\Bar;
use \League\Container\Container;
class CachedReflection
{
private $instance;
private static $cached = [];
private $class;
public function __construct($class)
{
$this->class = $class;
if (!isset(self::$cached[$class])) {
self::$cached[$class] = new ReflectionClass($class);
}
}
public function get()
{
return self::$cached[$this->class];
}
}
if (isset($argv[1]) && $argv[1] == 'build')
{
$autowire = [];
$classes = [Foo::class, Bar::class];
foreach ($classes as $class) {
$ref = (new CachedReflection($class))->get();
$autowire[$class] = ['arguments' => []];
foreach ($ref->getConstructor()->getParameters() as $param) {
$autowire[$class]['arguments'][] = (string) $param->getType();
}
}
file_put_contents(__DIR__ . '/autowire.json', json_encode($autowire, JSON_PRETTY_PRINT));
}
$autowire = json_decode(file_get_contents(__DIR__ . '/autowire.json'), true);
$container = new Container();
foreach ($autowire as $id => $obj) {
$o = $container->add($id);
if (isset($obj['arguments']))
{
foreach ($obj['arguments'] as $argument) {
$o->addArgument($argument);
}
}
}
$foo = $container->get(Foo::class);
$bar = $container->get(Bar::class);
var_dump($foo, $bar);
die;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment