$container->set('cache.path', '/tmp/cache'); $container->register(CacheProvider::class, function (Container $c) { return new FileCache($c->get('cache.path')); }); $container->register(UserRepository::class, function (Container $c) { return new UserRepository($c->get(CacheProvider::class)); }); $repo = $container->get(UserRepository::class); ok($repo instanceof UserRepository); ok($repo->cache instanceof CacheProvider); eq($repo->cache->path, '/tmp/cache'); }); test('can alias names', function () { $container = new Container(); $container->register(FileCache::class, ['/tmp/foo']); $container->alias(CacheProvider::class, FileCache::class); eq($container->get(FileCache::class), $container->get(CacheProvider::class), 'alias return same singleton'); }); /** * @param ContainerInterface $container */ function test_case(ContainerInterface $container) { $repo = $container->get(UserRepository::class); ok($repo instanceof UserRepository); ok($repo->cache instanceof CacheProvider); eq($repo->cache->path, '/tmp/cache'); } test('can resolve dependencies using parameter names', function () { $container = (require __DIR__ . '/bootstrap-unbox.php'); test_case($container);
private $container; public function __construct(Container $factory) { $this->container = $factory; } public function run($path, $params) { list($controller, $action) = explode("/", $path); $class = ucfirst($controller) . "Controller"; $method = $action; $this->container->call([$this->container->create($class), $method], $params); } } ### bootstrap.php: $container = new Container(); $container->register("cache", function ($cache_path) { return new FileCache($cache_path); }); $container->alias(CacheProvider::class, "cache"); $container->register(UserRepository::class); $container->register(Dispatcher::class); ### config.php: $container->set("cache_path", "/tmp/cache"); ### index.php: $container->call(function (Dispatcher $dispatcher) { $path = "user/show"; // $path = $_SERVER["PATH_INFO"]; $params = array("user_id" => 123); // $params = $_GET; $dispatcher->run($path, $params); });