# Dependent
The Dependent component is in charge of providing handling for object dependencies that must be injected. The concept is well-known as dependency injection.
A Dependent is a class that expose dependencies required to be provided on instance creation.
# Implementing
DependentInterface describes the interface for the component in charge of defining a Dependent.
TIP
⏩ Use DependentTrait to quickly implement the DependentInterface
.
use Chevere\Interfaces\Dependent\DependentInterface;
use Chevere\Components\Dependent\Traits\DependentTrait;
class MyDependent implements DependentInterface
{
use DependentTrait;
// ...
}
# Defining Dependencies
The getDependencies
method allows to define the Dependencies required by Dependent.
use Chevere\Components\Dependent\Dependencies;
public function getDependencies(): DependenciesInterface
{
return (new Dependencies())
->withPut(
foo: 'FooType',
bar: 'BarType',
);
}
Use typed properties to add type-checking to dependencies.
private FooType $foo;
private BarType $bar;
# Accessing Dependencies
The method dependencies
is used to access Dependencies required by Dependent.
$dependent->dependencies();
# Passing dependencies
Method withDependencies
is used to pass dependencies.
/**
* @var FooType $fooInject
* @var BarType $barInject
*/
$dependent = (new MyDependent())
->withDependencies(
foo: $fooInject,
bar: $barInject
);
# Asserting dependencies
The method assertDependencies
asserts if a Dependent meets all dependencies.
$dependent->assertDependencies();
# Dependencies
The Dependencies component is in charge of collecting dependencies.
DependenciesInterface describes the interface for the component in charge of defining Dependencies.
# Creating Dependencies
use Chevere\Components\Dependent\Dependencies;
$dependencies = new Dependencies();
# Putting Dependencies
The withPut
method is used to pass named dependencies.
$dependencies->withPut(foo: 'FooType');
# Mappable tools
The keys
method access all dependency names.
$dependencies->keys(); // ['foo']
The count
method returns the dependencies count.
$dependencies->count(); // 1
The getGenerator
method returns a Generator that can be used to traverse dependencies.
foreach($dependencies->getGenerator() as $name => $className)
{
// $name = 'foo';
// $className = 'FooType';
}