Skip to content

Helper function diGet() ​

The helper function diGet() injects a dependency via a container identifier [1]; this is equivalent to calling the container's get() method.

In cases where a parameter of a method or a callable type[2] is specified using user-defined types (such as PHP classes, built-in PHP classes, or enums), there is no need to use the diGet() helper function; the container automatically injects the dependency based on the configuration.

The diGet() helper function should be used for dependency injection when the container cannot automatically determine the type of dependency. For example, if a method parameter is defined with the mixed type or as a composite type (such as an intersection or union of class types), the helper function serves to clarify exactly which value from the container should be injected into that parameter.

Function signature:

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

\Kaspi\DiContainer\diGet(
    string $containerIdentifier
): DiDefinitionNoArgumentsInterface

Parameters:

  • $containerIdentifier – container identifier [1:1].

The helper function has no additional methods.

Example of injection into a parameter of type mixed ​

PHP classes:

php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Foo
{
    public function __construct(public readonly mixed $entry) {}
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Bar
{
    // …
}

It is necessary to inject the PHP class \App\Services\Foo into the $entry parameter of the PHP class \App\Services\Bar.

php
<?php
declare(strict_types=1);

// file: /app/src/container_build.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->entry instanceof Bar);
php
<?php
declare(strict_types=1);

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

use App\Service\{Foo, Bar};

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


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

Run the following command in the terminal:

shell
php /app/src/container_build.php

A message like the following will appear:

console
(bool) true

Cookbook ​

The “Cookbook” section provides examples of how to refine an ad by incorporating parameters:


  1. 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. ↩︎ ↩︎

  2. The callable type represents values ​​or expressions that can be invoked as a function. See the description in the PHP documentation. ↩︎