solophp / container
Dependency Injection Container implementing WritableContainerInterface
v2.3.0
2026-03-13 14:26 UTC
Requires
- php: >=8.1
- solophp/contracts: ^1.0
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^4.0
README
Lightweight PSR-11 dependency injection container with auto-wiring, interface binding, and singleton caching.
Features
- PSR-11 Compatible — Implements
WritableContainerInterfacefromsolophp/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 Invalidation —
set()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 foundSolo\Container\Exceptions\ContainerException— service cannot be resolved
Requirements
- PHP 8.1+
License
MIT License. See LICENSE for details.