georgeff / container
A light weight DI container
1.0.0
2026-02-07 20:27 UTC
Requires
- php: ^8.2
- psr/container: ^2.0
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.0
- squizlabs/php_codesniffer: ^3.11
README
A lightweight dependency injection container implementing PSR-11.
Installation
composer require georgeff/container
Usage
Registering Definitions
Register a definition by providing an ID and a callable factory. The container instance is passed to the factory.
use Georgeff\Container\Container; $container = new Container(); $container->add('database', function (Container $container) { return new DatabaseConnection('localhost', 'mydb'); });
Shared Definitions
Shared definitions are resolved once and the same instance is returned on subsequent calls.
$container->addShared('database', function (Container $container) { return new DatabaseConnection('localhost', 'mydb'); }); // Or pass true as the third argument to add() $container->add('database', function (Container $container) { return new DatabaseConnection('localhost', 'mydb'); }, true);
Resolving Definitions
$db = $container->get('database');
Aliases
Aliases allow you to resolve a definition by an alternate name, useful for binding interfaces to implementations.
$container->addShared(DatabaseConnection::class, function (Container $container) { return new DatabaseConnection('localhost', 'mydb'); }); $container->addAlias(DatabaseConnection::class, ConnectionInterface::class); // Resolves the DatabaseConnection definition $db = $container->get(ConnectionInterface::class);
Checking for Definitions
$container->has('database'); // true $container->has('nonexistent'); // false
Exceptions
DefinitionNotFoundException— thrown when getting a definition that does not exist or aliasing a non-existing definition. Implements PSR-11NotFoundExceptionInterface.CircularDependencyException— thrown when a circular dependency is detected during resolution. Implements PSR-11ContainerExceptionInterface.ContainerException— thrown when an error occurs during definition resolution. Implements PSR-11ContainerExceptionInterface.
License
MIT