dependency injector php
Dip is a PHP library which provides dependency injection functionality. It is lightweight and bare bones with a simple API.
install
composer add sd512/dip
use
Given the following two classes
namespace Garage
{
class Engine {}
class Truck
{
public $engine;
public function __construct(Engine $engine)
{
$this->engine = $engine;
}
}
}
a new instance of Truck
can be created simply by calling
$dip = new Dip();
$truck = $dip->provide(\Garage\Truck::class);
No further configuration is required in this case. A new Truck
instance will be returned
complete with a new Engine
.
In more general terms, an instance of a class C can be created by Dip if either one of the following
requirements are met:
- C has no constructor arguments
- All of C's constructor arguments are type-hinted and of types are creatable by Dip themselves.
Classes for which constructor args cannot automatically determined require an implementation of
Producer
in order to be generated.
Consider the Cookie class:
class Cookie
{
public function __construct($chocChipCount, $isWarm)
{
// ...
}
}
Dip cannot automatically determine values for $chocChipCount
or $isWarm
, so a producer
must be used.
class CookieProducer implements Producer
{
function forClass()
{
return Cookie::class;
}
function produce()
{
return new Cookie(7, true);
};
}
$dip = new Dip();
$dip->registerProducer(new CookieProducer());
$cookie = $dip->provide(Cookie::class); // ok
Lastly, any object provided by Dip will have all of it's @inject
annotated public fields
resolved and set with an appropriate value. All fields annotated with @inject
must also have an
@var
annotation to provide the type hint.
class SnareDrum {}
class DrumSet
{
/**
* @inject
* @var SnareDrum
*/
public $snare;
}
$dip = new Dip();
$dip->provide(DrumSet::class);
If an object has been previously instantiated it's fields can be manually injected by calling
// previously
// $drumSet = $new DrumSet();
$dip->inject($drumSet);
Dip protects against injecting more than once by throwing an exception if injecting into non null fields.
notes
Requires PHP 7.2+
Named instance support is coming for reusing instances (as a singleton for example)
links
Source RepoIssue Tracker