0

I have a use case where we're using Auryn to wire up our classes, and I need to inject a different configuration class depending on a parameter's value.

Auryn's documentation gives an example of injecting a dependency:

interface Engine {}
class V8 implements Engine {}
class Car {
    private $engine;
    public function __construct(Engine $engine) {
        $this->engine = $engine;
    }
}

$injector = new Auryn\Injector;

// Tell the Injector class to inject an instance of V8 any time
// it encounters an Engine type-hint
$injector->alias('Engine', 'V8');

$car = $injector->make('Car');
var_dump($car instanceof Car); // bool(true)

But what if I also had

class Hybrid implements Engine

and I needed to determine on a case by case basis whether I get a V8 or a Hybrid out of Auryn when it makes its dependencies?

This is a contrived example based on Auryn's documentation, in the real code the class requires a configuration to be passed at construction. However the basic issue is the same.

GordonM
  • 31,179
  • 15
  • 87
  • 129

1 Answers1

0

You can use $injector->define() like so:

<?php
$injector = new Auryn\Injector;
$injector->define('Car', ['engine' => 'Hybrid']);
$car = $injector->make('Car');

var_dump($car instanceof Car); // true

Link: https://github.com/rdlowrey/auryn#injection-definitions

  • But then all Car objects would have Hybrid engine objects injected. I need some Cars to have Hybrid engines and others to have V8 engines. – GordonM Nov 19 '18 at 10:59
  • You can create child class and inject the right dependency to each child. – Enea Overclokk Nov 23 '18 at 18:21
  • In theory for some cases that's an option but that's hardly very elegant, creating classes purely to get the DI to work the way you want. And you can't do that in some cases – GordonM Nov 24 '18 at 10:52
  • Maybe you can use the definition on the fly https://github.com/rdlowrey/auryn#specifying-injection-definitions-on-the-fly `$car = $injector->make('Car', ['engine' => 'Hybrid']);` when you need V8 just inject it `$car = $injector->make('Car', ['engine' => 'V8']);` – Enea Overclokk Dec 12 '18 at 07:35