Skip to content

Helper function diProxyClosure() ​

The helper function diProxyClosure() 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 incorporating heavy dependencies that require a long initialization time or resource-intensive computations.

IMPORTANT

Be sure to type-hint the parameter[1] as \Closure or callable for dependency injection via the diProxyClosure() helper function.

php
 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 diProxyClosure() helper function.

Function signature:

php
use Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionTagArgumentInterface;

\Kaspi\DiContainer\diProxyClosure(
    string $containerIdentifier,
    ?bool $isSingleton = null,
): DiDefinitionTagArgumentInterface

Parameters:

  • $containerIdentifier – container identifier [2].
  • $isSingleton – The container will return the same object instance (singleton pattern). If set to null, the value will be determined based on the container configuration.

The diProxyClosure() function returns an object that provides the following methods:

  • bindTag() – adds a tag containing metadata for identification.

bindTag() ​

Tags allow a lazy definition to be associated with a collection of elements marked with a single tag.

The bindTag() method is defined by the \Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionTagArgumentInterface interface.

Method signature:

php
DiDefinitionTagArgumentInterface::bindTag(
    string $name,
    array $options = [],
    null|int|string $priority = null
)

TIP

For more details, see the guide on working with tags.

Container identifier for lazy definition ​

To make a "lazy" definition accessible via the container's get() and has() methods, you must specify a container identifier[2:1] in the configuration file that corresponds to the declared definition.

A resource-intensive PHP class that requires a lengthy initialization process:

Bar.php
php
<?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 container method $container->get('services.bar_lazy') should return a "lazy" object of the class \App\Services\Bar.

php
<?php
declare(strict_types=1);

// file: /app/src/container.php

require_once __DIR__.'/../vendor/autoload.php';

use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Bar;

$container = (new DiContainerBuilder())
    ->load('/app/config/lazy_entries.php')
    ->build();

$barLazy = $container->get('services.bar_lazy');

var_dump($barLazy instanceof Closure);
var_dump(($barLazy)() instanceof Bar);
php
<?php
declare(strict_types=1);

// file: /app/config/lazy_entries.php

use App\Services\Bar;

use function Kaspi\DiContainer\diProxyClosure;

return static function(): Generator {
    yield 'services.bar_lazy' => diProxyClosure(
        Bar::class,
        isSingleton: true
    );
};

Run the following command in the terminal:

shell
php /app/src/container.php

A message like the following will appear:

console
bool(true)
bool(true)

Example of implementing a parameter with deferred initialization ​

PHP classes:

php
<?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.
     */
}
php
<?php
declare(strict_types=1);

// file: /app/src/Services/Foo.php

namespace App\Services;

use Closure;

final class Foo
{
    /**
     * @param Closure(): Bar $barProxy
     */
    public function __construct(private readonly Closure $barProxy) {}

    public function getBar(): Bar
    {
        return ($this->barProxy)();
    }
}

The PHP class \App\Services\Bar performs resource-intensive calculations upon initialization; it should be injected into the $barProxy parameter of the \App\Services\Foo class constructor using a "lazy" object initialization technique, implemented via PHP's built-in \Closure class.

php
<?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())
    ->load('/app/config/services.php')
    ->build();

$foo = $container->get(Foo::class);

var_dump($foo->getBar() instanceof Bar);
php
<?php
declare(strict_types=1);

// file: /app/config/services.php

use App\Services\{Foo, Bar};

use function Kaspi\DiContainer\{diAutowire, diProxyClosure};

return static function(): Generator {
    yield diAutowire(Foo::class)
        ->bindArguments(
            barProxy: diProxyClosure(Bar::class)
        );
};

Run the following command in the terminal:

shell
php /app/src/container.php

A message like the following will appear:

console
bool(true)

TIP

Use PhpDocBlock for hints and autocompletion in your IDE:

php
  /**
   * @param Closure(): Bar $barProxy
   */
 public function __construct(private readonly Closure $barProxy) {}

  1. Type hints – the specification of an expected data type for method parameters, such as the name of a specific class or interface. ↩︎

  2. A container ID is a string name (or a class/interface name) used to register a service or object within a container and to retrieve it via the get() method. ↩︎ ↩︎