SetupPriority attribute
The \Kaspi\DiContainer\Attributes\SetupPriority attribute modifies the order in which dependencies are injected via the setter methods of a PHP class; it is used in conjunction with the Setup and SetupImmutable attributes.
Attribute configuration:
\Attribute::TARGET_METHOD
Attribute signature:
\Kaspi\DiContainer\Attributes\SetupPriority::__construct(
int $priority = 0
)Parameters:
$priority– call priority.
The higher the value of the $priority parameter, the earlier the dependency will be injected via a setter method.
Example of changing the priority of setter methods
PHP classes:
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use function array_values;
final class Foo
{
private array $injectedClass = [];
// …
public function bar(Bar $bar): void
{
$this->injectedClass[Bar::class] = $bar;
}
public function baz(Baz $baz): void
{
$this->injectedClass[Baz::class] = $baz;
}
public function getInjectedClass(): array
{
return array_values($this->injectedClass);
}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
final class Bar
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Services/Baz.php
namespace App\Services;
final class Baz
{
// …
}Dependency injection must be configured via setter methods for \App\Services\Foo::bar() and \App\Services\Foo::baz().
The dependency must first be injected via the setter method \App\Services\Foo::baz(), followed by the injection via \App\Services\Foo::bar().
Use the \Kaspi\DiContainer\Attributes\SetupPriority attribute on the \App\Services\Foo::baz() method to specify the order of injection via the setter methods.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use Kaspi\DiContainer\Attributes\Setup;
use Kaspi\DiContainer\Attributes\SetupPriority;
use function array_values;
final class Foo
{
private array $injectedClass = [];
// …
#[Setup]
public function bar(Bar $bar): void
{
$this->injectedClass[Bar::class] = $bar;
}
#[Setup]
#[SetupPriority(10)]
public function baz(Baz $baz): void
{
$this->injectedClass[Baz::class] = $baz;
}
public function getInjectedClass(): array
{
return array_values($this->injectedClass);
}
}<?php
declare(strict_types=1);
// file: /app/src/container.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\{Foo, Bar, Baz};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$foo = $container->get(Foo::class);
foreach ($foo->getInjectedClass() as $injectedClass) {
var_dump($injectedClass::class);
}Run the following command in the terminal:
php /app/src/container.phpA message like the following will appear:
string(16) "App\Services\Baz"
string(16) "App\Services\Bar"