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:
use Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionNoArgumentsInterface;
\Kaspi\DiContainer\diGet(
string $containerIdentifier
): DiDefinitionNoArgumentsInterfaceParameters:
$containerIdentifier– container identifier [1:1].
The helper function has no additional methods.
Example of injection into a parameter of type mixed
PHP classes:
<?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
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
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
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:
php /app/src/container_build.phpA message like the following will appear:
(bool) trueCookbook
The “Cookbook” section provides examples of how to refine an ad by incorporating parameters:
- Dependency injection of a PHP class that implements a specific interface.
- Dependency injection for union type parameters.
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. ↩︎ ↩︎The
callabletype represents values or expressions that can be invoked as a function. See the description in the PHP documentation. ↩︎