Injecting the right config with Auryn

89 views Asked by At

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.

1

There are 1 answers

4
Enea Overclokk On

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