xp-forge / inject

Dependency injection for the XP Framework
0 stars 0 forks source link

Add Injector::implementations() to select implementations for a given type #32

Open thekid opened 4 months ago

thekid commented 4 months ago

Previously:

use inject\{Injector, ProvisionException};

class Prompts {
  public function __construct(private Injector $inject) { }

  public function send($prompt, $model) {
    if ($instance= $this->injector->get(Model::class, $model)) {
      return $instance->send($prompt);
    }
    throw new ProvisionException('No such model '.$model);
  }
}

$prompts= (new Injector(/* ... */))->get(Prompts::class);

New alternative:

use inject\Injector;

class Prompts {

  /** @param inject.Implementations<Model> $implementations */
  public function __construct(private $implementations) { }

  public function send($prompt, $model) {
    return $this->implementations->named($model)->send($prompt);
  }
}

$prompts= (new Injector(/* ... */))->get(Prompts::class);
thekid commented 4 months ago

This will supersede providers.

Before

$provider= $injector->get('inject.Provider<com.example.writers.ReportWriter>');

// ...later on
$instance= $provider->get();

After

$implementations= $injector->implementations(ReportWriter::class);

// ...later on
$instance= $implementations->default();

Rollout

thekid commented 3 months ago

Alternative idea: Create inject.Injection superseding inject.Injector; only implementing new features there but already removing other APIs such as add(), args() and newInstance(). This would open a much faster path towards a new, leaner API.