public function register(Container $container) { $container->set('cache_path', '/tmp/cache'); $container->register(CacheProvider::class, function ($cache_path) { return new FileCache($cache_path); }); $container->register(UserRepository::class, function (CacheProvider $cache) { return new UserRepository($cache); }); }
}, [$container->ref('cache.path')]); $container->register(UserRepository::class, function (CacheProvider $cp) { return new UserRepository($cp); }, ['cp' => $container->ref('cache')]); $repo = $container->get(UserRepository::class); ok($repo instanceof UserRepository); ok($repo->cache instanceof CacheProvider); eq($repo->cache->path, '/tmp/cache'); }); test('can act as a factory', function () { $container = new Container(); $container->register(CacheProvider::class, function () { return new FileCache('/tmp/cache'); }); $repo = $container->create(UserRepository::class); ok($repo instanceof UserRepository); $another = $container->create(UserRepository::class); ok($repo !== $another); }); test('can override factory maps', function () { $container = new Container(); $container->set('cache.path', '/tmp/cache'); $container->register(CacheProvider::class, FileCache::class, [$container->ref('cache.path')]); $repo = $container->create(UserRepository::class); eq($repo->cache->path, '/tmp/cache'); $repo = $container->create(UserRepository::class, [new FileCache('/my/path')]); eq($repo->cache->path, '/my/path'); }); configure()->enableCodeCoverage(__DIR__ . '/build/clover.xml', dirname(__DIR__) . '/src'); exit(run()); // exits with errorlevel (for CI tools etc.)
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); });