gacela-project/resolver

This package is abandoned and no longer maintained. The author suggests using the gacela-project/container package instead.

A minimalistic container dependency resolver

0.7.0 2024-07-06 11:07 UTC

This package is auto-updated.

Last update: 2024-07-06 11:16:42 UTC


README

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