Created
May 8, 2019 14:38
-
-
Save kobus1998/e7e149db14b104741367c7aa368041c8 to your computer and use it in GitHub Desktop.
Autowire container with league\container
This file contains hidden or 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 __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