Skip to content

gacela-project/container

Repository files navigation

Gacela Container

GitHub Build Status Scrutinizer Code Quality Scrutinizer Code Coverage Psalm Type-coverage Status MIT Software License

Installation

composer require gacela-project/container

Usage

Get an instance by class name.

You can define a map between an interface and the concrete class that you want to create (or use) when that interface is found during the process of auto-wiring via its constructor.

Container

This container will auto-wire all inner dependencies from that class. Depending on the type of dependency it will resolve it differently:

  • primitive types: it will use its default value
  • classes: it will instantiate it, and if they have dependencies, they will be resolved recursively as well.
  • interfaces: they will be resolved according to the bindings injected via the Container's constructor.
$bindings = [
  AbstractString::class => StringClass::class,
  ClassInterface::class => new ConcreteClass(/* args */),
  ComplexInterface::class => new class() implements Foo {/** logic */},
  FromCallable::class => fn() => new StringClass('From callable'),
];

$container = new Container($bindings);

$instance = $container->get(YourClass::class);

//////////////////////////////////////////////
# Extra: you can resolve closures on-the-fly using the container bindings
$resolved = $container->resolve(function (ComplexInterface $i) {
    // your custom logic
    return $i->...; 
});

Example

A usage example in the Gacela Framework: AbstractClassResolver