A PSR-11 dependency injection container for PHP 8.4+. Most classes need no configuration: the container builds them from their constructors and shares one instance of each.
- Auto-wiring — a class is built from its constructor, and its dependencies the same way.
- Factories and bindings —
set()registers a factory,bind()points an interface at its implementation. - Shared instances — each service is built once;
reset()drops them all, for example between the jobs of a worker. - Lazy services —
lazy()and#[Lazy]defer construction with native lazy objects and break circular dependencies. - Injection by id —
#[Inject('id')]resolves a parameter its type cannot tell apart. - The container itself — a parameter typed
Container,ContainerInterfaceorWritableContainerInterfacereceives the container, with nothing to register. - Cycle detection — a circular dependency fails at once and names the whole chain.
- Guaranteed types —
get(Foo::class)returns aFooor throws, and PHPStan sees aFoo: no casts at level max, throughWritableContainerInterfaceas well.
composer require solophp/containerRequires PHP 8.4+: lazy() and #[Lazy] build native lazy objects.
use Solo\Container\Container;
$container = new Container();
// A factory receives the container
$container->set(Database::class, fn($c) => new Database($c->get(Config::class)->dsn));
// An interface resolves to the class bound to it, which must implement it
$container->bind(LoggerInterface::class, FileLogger::class);
// Anything else is built from its constructor
$users = $container->get(UserRepository::class); // a UserRepository, to PHPStan as wellUpgrading from 3.x? See Upgrading to 4.0.
- Installation
- Quick Start
- Static Analysis
- Upgrading to 4.0
- Services & Factories
- Auto-wiring
- Interface Binding
- Lazy Services
- Injection by Id
- Circular Dependencies
- API Reference
MIT. See LICENSE.