di

Dependency injection and service container with singletons and cycle detection.

v1.0.0Application & logicbundledimport "di";
Overview Installation Documentation Examples

Overview

Lightweight Dependency Injection / Service Container for HolyPHP.

Supports transient bindings (bind), lazy singletons (singleton), pre-built values (instance), service resolution (make / get), introspection (has, keys), and automatic circular dependency detection with clear error messages.

bundled — works offline container ioc singleton

Quick start

import "di";

class Config {
    public string $dsn;
    public function __construct(string $dsn) {
        $this->dsn = $dsn;
    }
}

class Database {
    public string $dsn;
    public function __construct(string $dsn) {
        $this->dsn = $dsn;
    }
}

$c = di_container();

// Register a pre-built instance
$c->instance("config", new Config("postgres://localhost/app"));

// Register a lazy singleton
$c->singleton("db", function (Container $container) {
    $cfg = $container->get("config");
    return ["dsn" => $cfg["dsn"]];
});

// Register a transient factory (new value on every make/get)
$c->bind("request_id", function (Container $container) {
    return "req-" . microtime(true);
});

$db = $c->get("db");
println($db->dsn); // postgres://localhost/app

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install di

This adds the library to hphp.yaml, installs it into .hphp/packages/di/ and pins the exact version in hphp.lock:

require:
  di: "^1.0"

Use it

import "di";

di is bundled with the compiler, so import "di"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install di          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install di
Packagedi
Version1.0.0 (follows the compiler)
Entry filedi.hphp
Sourcepackages/lib/di ↗

Documentation

API Reference

Helper Functions

di_container(): Container

Creates and returns a new Container instance.

---

class Container

bind(string $id, $factory): Container

Registers a transient service factory. The $factory callable receives the Container instance as its sole argument and is invoked on every make($id) / get($id) call. Re-binding an existing $id replaces the previous registration. Returns $this for chaining.

singleton(string $id, $factory): Container

Registers a lazy singleton factory. The $factory callable receives the Container instance and is invoked at most once; the returned value is cached and reused on subsequent make($id) / get($id) calls. Returns $this for chaining.

instance(string $id, $value): Container

Registers an already-instantiated object or value directly under $id. Returns $this for chaining.

make(string $id)

Resolves and returns the service registered under $id. Throws an Exception if $id is empty, not registered, or part of a circular dependency chain.

get(string $id)

Alias for make($id).

has(string $id): bool

Returns true if a binding, singleton, or instance is registered under $id, or false otherwise.

keys(): array

Returns an array of all registered service IDs.

forget(string $id): bool

Removes the registration (and cached singleton instance, if any) for $id. Returns true if the service existed, false otherwise.

clear(): void

Removes all registrations and cached instances from the container.

Error Handling

All errors throw Exception with a di: prefix:

try {
    $c->get("missing");
} catch (Exception $e) {
    println($e->getMessage()); // di: service 'missing' is not registered
}

Examples

01Quick start

Bundled with the compiler — import "di"; works offline in any file, or add it to a project with hphp install di.

import "di";

class Config {
    public string $dsn;
    public function __construct(string $dsn) {
        $this->dsn = $dsn;
    }
}

class Database {
    public string $dsn;
    public function __construct(string $dsn) {
        $this->dsn = $dsn;
    }
}

$c = di_container();

// Register a pre-built instance
$c->instance("config", new Config("postgres://localhost/app"));

// Register a lazy singleton
$c->singleton("db", function (Container $container) {
    $cfg = $container->get("config");
    return ["dsn" => $cfg["dsn"]];
});

// Register a transient factory (new value on every make/get)
$c->bind("request_id", function (Container $container) {
    return "req-" . microtime(true);
});

$db = $c->get("db");
println($db->dsn); // postgres://localhost/app
Try it
hphp install di
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_di.hphp.