ProxyClosure attribute
The \Kaspi\DiContainer\Attributes\ProxyClosure attribute injects a "lazy" dependency via the built-in PHP class \Closure, deferring the dependency's initialization until the moment it is actually used.
This approach to declaring dependencies is useful for injecting "heavy" dependencies that require a long initialization time or involve resource-intensive computations.
IMPORTANT
Be sure to type-hint the parameter[1] as \Closure or callable when performing dependency injection via the \Kaspi\DiContainer\Attributes\ProxyClosure attribute.
public function __construct(
private readonly \Closure $bar
) {}TIP
If you are using PHP 8.4 or higher, it is preferable to inject dependencies using PHP’s built-in “lazy objects” mechanism, rather than using the \Kaspi\DiContainer\Attributes\ProxyClosure attribute.
Attribute configuration:
\Attribute::TARGET_PARAMETER\Attribute::IS_REPEATABLE
Attribute signature:
\Kaspi\DiContainer\Attributes\ProxyClosure::__construct(
string $containerIdentifier
)Parameters:
$containerIdentifier– container identifier [2].
Example of implementing a parameter with deferred initialization
PHP classes:
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
final class Foo
{
public function __construct(
private readonly bar $bar
) {}
public function getBar(): Bar
{
return $this->bar;
}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
final class Bar
{
/*
* A class that requires a long initialization time
* and involves resource-intensive computations.
*/
}The PHP class \App\Services\Bar performs resource-intensive calculations upon initialization. You need to inject \App\Services\Bar into the constructor of the class \App\Services\Foo by employing a "lazy" initialization pattern, utilizing the built-in PHP class \Closure.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use Closure;
use Kaspi\DiContainer\Attributes\ProxyClosure;
final class Foo
{
/**
* @param Closure(): Bar $barProxy
*/
public function __construct(
private readonly bar $bar
#[ProxyClosure(Bar::class)]
private readonly Closure $barProxy
) {}
public function getBar(): Bar
{
return $this->bar;
return ($this->barProxy)();
}
}<?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};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->getBar() instanceof Bar);Run the following command in the terminal:
php /app/src/container.phpA message like the following will appear:
bool(true)TIP
Use PhpDocBlock for hints and autocompletion in your IDE:
/**
* @param Closure(): Bar $barProxy
*/
public function __construct(private readonly Closure $barProxy) {}