A dependency injector resolves the dependencies of your class and makes sure that the correct objects are injected when the class is instantiated.
Basic Instantiation
If a class only asks for concrete dependencies you can use the Injector to inject them without specifying any injection definitions:
class SomeDep {}
class AnotherDep {}
class MyClass {
public $dep1;
public $dep2;
public function __construct(SomeDep $dep1, AnotherDep $dep2) {
$this->dep1 = $dep1;
$this->dep2 = $dep2;
}
}
$injector = new Auryn\Injector;
$myObj = $injector->make('MyClass');
In this scenario you can use the Injector to automatically provision MyClass
with the required SomeDependency
and AnotherDependency
class instances.
Injection Definitions
interface Engine {}
class V8 implements Engine {}
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
}
//...
$injector->define('Car', ['engine' => 'V8']);
Because the Car
constructor parameter we needed to define was named $engine
, our definition specified an engine
key whose value was the name of the class (V8
) that we want to inject.
Non-Class Parameters (Raw values)
$injector->define(TemplateDirectory::class, [':rootDirectory' => ROOT_DIR]);
// Equals to:
$injector->define(TemplateDirectory::class, [ROOT_DIR]);
The colon character preceding the parameter names tells the Injector that the associated values ARE NOT class names. If the colons had been omitted above, auryn would attempt to instantiate classes of the names specified in the string and an exception would result.
Alias
$injector->alias('Engine', 'V8');
Share
By sharing an instance of a class, Auryn\Injector will always use that instance when provisioning classes that type-hint the shared class.
class Person {
public $name = 'John Snow';
}
$injector = new Auryn\Injector;
$injector->share('Person');
$person = $injector->make('Person');
var_dump($person->name); // John Snow
$person->name = 'Arya Stark';
$anotherPerson = $injector->make('Person');
var_dump($anotherPerson->name); // Arya Stark
var_dump($person === $anotherPerson); // bool(true) because it's the same instance!
NOTE: Once the Injector caches a shared instance, call-time definitions passed to
Auryn\Injector::make
will have no effect. Once shared, an instance will always be returned for instantiations of its type until the object is un-shared or refreshed:
Instantiation Delegates
Often factory classes/methods are used to prepare an object for use after instantiation. auryn allows you to integrate factories and builders directly into the injection process by specifying callable instantiation delegates on a per-class basis.
$TwigTemplateRendererFactory = function () use ($injector) {
$factory = $injector->make(TwigTemplateRendererFactory::class);
return $factory->create();
};
$injector->delegate(
TemplateRenderer::class,
$TwigTemplateRendererFactory
);