cheerios / cheerios-container
Requires
- php: >=8.4
Requires (Dev)
- phpstan/phpstan: ^2.1
- symfony/var-dumper: ^5
This package is not auto-updated.
Last update: 2026-04-11 02:32:50 UTC
README
This is a minimal and configurable implementation of a PHP dependency injection container.
Usage
Creating an instance of a class
Calling ->get() or invoking the container will yield an instance of the provided class name.
$container = Container::getInstance(); $instance = $container->get(SomeClass::class); $otherInstance = $container(SomeClass::class); // __invoke() is a short-hand for get()
Setting default arguments and passing arguments to the Container
Default arguments can be set for classes that have primitive arguments in their constructors. Additionally, arguments can be passed to ->get() or __invoke() and they will override any conflicting pre-registered value. Trying to create an instance of a class with a primitive argument without providing a value will throw.
$container = Container::getInstance() ->registerArgs(SomeClass::class, [ "argumentOne" => "hello", "argumentTwo" => "overwrite me!", ]); $instance = $container( class: SomeClass::class, args: ["argumentTwo" => "world"] );
Setting strategies
Strategies skip the Container's resolver entirely, as well as registered interfaces and arguments.
$container->registerStrategy(SpecialClass::class, function() { return specialFunctionThatReturnsASpecialClassInstance(); }); $specialInstance = $container(SpecialClass::class);
Registering a default for an interface
The provided class name is instantiated when the Container is called on its interface.
$container->registerInterface(SomeInterface::class, SomeClass::class); $instance = $container(SomeInterface::class);