# Dependent

The Chevere\Components\Dependent namespace provides components for providing handling for object dependencies that must be injected. The concept is well-known as dependency injection (opens new window).


A class that expose dependencies required to be provided on instance creation is known as a dependent.

# Implementing

DependentInterface describes the interface for the component in charge of defining a Dependent.


⏩ 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())
            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.


# Passing dependencies

Method withDependencies is used to pass dependencies.

 * @var FooType $fooInject
 * @var BarType $barInject
$dependent = (new MyDependent())
        foo: $fooInject,
        bar: $barInject

# Asserting dependencies

The method assertDependencies asserts if a Dependent meets all dependencies.


# 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';