solophp / container
Dependency Injection Container implementing WritableContainerInterface
Requires
- php: >=8.4
- solophp/contracts: ^1.7
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Lightweight PSR-11 dependency injection container for PHP 8.4+. Register factories, bind interfaces to implementations and let constructor auto-wiring build the rest: each service is built once and shared. get(Foo::class) returns a Foo or throws — the container checks it — and PHPStan sees it as a Foo, so code analysed at level max needs no casts after it.
Installation
composer require solophp/container
Requires PHP 8.4+: lazy() and #[Lazy] build native lazy objects.
Example
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 well
lazy() and #[Lazy] defer construction and break circular dependencies; #[Inject('id')] resolves a parameter its type cannot tell apart. Service providers typed against WritableContainerInterface from solophp/contracts get the same typed get().
Upgrading from 3.x? See Upgrading to 4.0.
Documentation
- Installation
- Quick Start
- Static Analysis
- Upgrading to 4.0
- Services & Factories
- Auto-wiring
- Interface Binding
- Lazy Services
- Injection by Id
- Circular Dependencies
- API Reference
License
MIT. See LICENSE.