solophp/container

Dependency Injection Container implementing WritableContainerInterface

Maintainers

Package info

github.com/SoloPHP/Container

pkg:composer/solophp/container

Statistics

Installs: 114

Dependents: 2

Suggesters: 2

Stars: 0

Open Issues: 0

v2.3.0 2026-03-13 14:26 UTC

This package is auto-updated.

Last update: 2026-03-13 14:29:59 UTC


README

Lightweight PSR-11 dependency injection container with auto-wiring, interface binding, and singleton caching.

Latest Version on Packagist PHP Version License Coverage

Features

  • PSR-11 Compatible — Implements WritableContainerInterface from solophp/contracts
  • Auto-wiring — Automatic dependency resolution via constructor reflection
  • Interface Binding — Bind abstracts to concrete implementations
  • Singleton Caching — Each service resolved once and cached
  • Cache Invalidationset() invalidates cached instance, reset() clears all
  • Service Factories — Register services as callable factories

Installation

composer require solophp/container

Quick Example

use Solo\Container\Container;

$container = new Container();

// Register a service factory
$container->set(Database::class, fn($c) => new Database('localhost', 'mydb'));

// Bind interface to implementation
$container->bind(LoggerInterface::class, FileLogger::class);

// Resolve with auto-wired dependencies
$repo = $container->get(UserRepository::class);

Usage

Constructor Registration

$container = new Container([
    'config' => fn() => new Config('config.php'),
    'cache'  => fn($c) => new Cache($c->get('config')),
]);

Auto-wiring

The container automatically resolves class dependencies via constructor reflection:

class UserRepository
{
    public function __construct(
        private Database $database,
        private LoggerInterface $logger
    ) {}
}

// Database and LoggerInterface resolved automatically
$repo = $container->get(UserRepository::class);

Interface Binding

$container->bind(LoggerInterface::class, FileLogger::class);
$container->bind(CacheInterface::class, RedisCache::class);

Re-registering Services

set() invalidates the cached instance, so the next get() uses the new factory:

$container->set(Connection::class, fn() => new Connection('db1'));
$conn1 = $container->get(Connection::class); // Connection to db1

$container->set(Connection::class, fn() => new Connection('db2'));
$conn2 = $container->get(Connection::class); // Connection to db2

Resetting All Instances

When a root dependency changes and the entire dependency tree needs rebuilding:

$container->reset(); // All cached instances cleared

Error Handling

  • Solo\Container\Exceptions\NotFoundException — service not found
  • Solo\Container\Exceptions\ContainerException — service cannot be resolved

Requirements

  • PHP 8.1+

License

MIT License. See LICENSE for details.