solophp / container
PSR-11 compatible Dependency Injection Container
v2.0.0
2025-08-02 11:22 UTC
Requires
- php: >=8.1
- psr/container: ^2.0
Requires (Dev)
- phpunit/phpunit: ^10.0
- squizlabs/php_codesniffer: ^3.7
README
A lightweight, PSR-11 compliant dependency injection container for PHP applications.
Installation
You can install the package via composer:
composer require solophp/container
Requirements
- PHP 8.1 or higher
- Composer 2.0 or higher
Basic Usage
use Solo\Container\Container; // Create a new container $container = new Container(); // Register a service $container->set('database', function($container) { return new Database('localhost', 'mydb', 'user', 'pass'); }); // Bind an interface to a concrete implementation $container->bind(LoggerInterface::class, FileLogger::class); // Get a service $db = $container->get('database');
Features
- PSR-11 Compatible
- Automatic dependency resolution
- Interface binding
- Singleton instances
- Constructor injection
- Service factories
Advanced Usage
Auto-Resolution
The container can automatically resolve class dependencies:
class UserRepository { public function __construct( private Database $database, private LoggerInterface $logger ) {} } // The container will automatically resolve Database and LoggerInterface $userRepo = $container->get(UserRepository::class);
Multiple Services Registration
$container = new Container([ 'config' => fn() => new Config('config.php'), 'cache' => fn($c) => new Cache($c->get('config')), ]);
Interface Binding
$container->bind(LoggerInterface::class, FileLogger::class); $container->bind(CacheInterface::class, RedisCache::class);
Development
Running Tests
composer test
Code Style
Check code style:
composer cs
Fix code style:
composer cs-fix
Error Handling
The container throws two types of exceptions:
Solo\Container\Exceptions\NotFoundException
: When a requested service is not foundSolo\Container\Exceptions\ContainerException
: When there's an error resolving a service
License
The MIT License (MIT). Please see License File for more information.