Skip to content

Helper function diCallable() ​

The helper function diCallable() injects a dependency by invoking the specified callable type[1].

Function signature:

php
use Kaspi\DiContainer\Interfaces\DiDefinition\{
    DiDefinitionArgumentsInterface as Args,
    DiDefinitionTagArgumentInterface as Tag,
};

\Kaspi\DiContainer\diCallable(
    callable $definition,
    ?bool $isSingleton = null
): Args & Tag

Parameters:

  • $definition – the callable type.
  • $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 diCallable() function returns an object that provides the following methods:

  • bindArguments() – specifies arguments for the function parameters.
  • bindTag() – adds a tag containing metadata to the definition.

bindArguments() ​

Passing arguments for the parameters of a callable type.

The bindArguments() method for defining parameters is described by the \Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionArgumentsInterface interface.

Method signature:

php
DiDefinitionArgumentsInterface::bindArguments(
    mixed ...$argument
)

Parameters:

  • $argument – arguments.

When specifying how a dependency should be injected into a particular parameter using bindArguments(), you can use named arguments.

If the method does not explicitly specify how a dependency should be injected into a given parameter, the container will handle the injection automatically based on its configuration.

TIP

  • The $argument parameter in bindArguments() can accept helper functions such as diGet(), diValue(), diAutowire(), and others.
  • For injecting scalar-type dependencies, it is recommended to use container parameters.

WARNING

The bindArguments() method overwrites any previously added arguments.

Example of dependency injection via the bindArguments() method ​

PHP classes:

php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Baz
{
    // …

    public static function factoryMethod(Bar $bar, string $name): string
    {
        return $name .' '. $bar->doSomething();
    }
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Bar
{
    // …

    public function doSomething(): string
    {
        return 'dolor sit amet';
    }
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Foo
{
    public function __construct(public readonly string $value) {}
}

In the callable_entries.php configuration file, you must declare the PHP class \App\Services\Foo and specify that a dependency should be injected into the $value parameter using a callable type[1:1] — specifically, \App\Services\Baz::factoryMethod().

For the \App\Services\Baz::factoryMethod() method, you must configure the injection of a scalar value into the $name parameter using the bindArguments() method; the container will automatically inject the dependency for the $bar parameter based on the existing configuration.

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;

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

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

var_dump($foo->value);
php
<?php
declare(strict_types=1);

// file: /app/config/callable_entries.php

use App\Services\{Foo, Baz};

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

return static function(): Generator {
    yield diAutowire(Foo::class)
        ->bindArguments(
            diCallable([Baz::class, 'factoryMethod'])
                ->bindArguments(
                    name: 'Lorem ipsum'
                )
        );
};

Run the following command in the terminal:

shell
php /app/src/container.php

A message like the following will appear:

console
string(26) "Lorem ipsum dolor sit amet"

bindTag() ​

Tags allow a declared callable type to be associated with a collection of elements marked with the same 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 the invoked type ​

To ensure that a callable type is accessible via the container’s get() and has() methods, you must specify the corresponding container identifier[2] in the configuration file and declare the callable type.

Example of declaring an identifier for a callable type ​

PHP classes:

php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Baz
{
    // …

    public static function factoryMethod(Bar $bar, string $name): string
    {
        return $name .' '. $bar->doSomething();
    }
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Bar
{
    // …

    public function doSomething(): string
    {
        return 'dolor sit amet';
    }
}

The container method $container->get('baz.factory_method') should return the result of executing the callable \App\Services\Baz::factoryMethod().

For the \App\Services\Baz::factoryMethod() method, configure the injection of a scalar value into the $name parameter using the bindArguments() method; the container will automatically inject the dependency for the $bar parameter based on its configuration.

php
<?php
declare(strict_types=1);

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

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

use Kaspi\DiContainer\DiContainerBuilder;

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

$result = $container->get('baz.factory_method');

var_dump($result);
php
<?php
declare(strict_types=1);

// file: /app/config/factory.php

use App\Services\Baz;

use function Kaspi\DiContainer\diCallable;

return static function(): Generator {
    yield 'baz.factory_method' => diCallable([Baz::class, 'factoryMethod'])
        ->bindArguments(
            name: 'Lorem ipsum'
    );
};

Run the following command in the terminal:

shell
php /app/src/container.php

A message like the following will appear:

console
string(26) "Lorem ipsum dolor sit amet"

“As-is” declaration of a callable type ​

In configuration files, you can specify a callable type[1:2] “as-is”, provided that the container is able to automatically inject the required dependencies based on its own configuration.

When a callable type is declared in a configuration file, the container converts it into a helper function called diCallable().

Example of declaring callable types “as-is” ​

PHP classes and functions:

php
<?php
declare(strict_types=1);

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

namespace App\Services;

use App\Helpers\Env;

use function getenv;

class Foo
{
    public function __construct(
        public readonly string $apiKey,
        public readonly bool $debug
    ) {}

    public static function makeForLocal(Env $env, bool $debug = true): self
    {
        $apiKey = $env::apiKey();

        return new self($apiKey, $debug);
    }
}
php
<?php
declare(strict_types=1);

// file: /app/src/Functions/functions.php

namespace App\Functions;

use App\Services\Foo;
use App\Helpers\Env;

use function getenv;

function staging_service(Env $env, bool $debug = false): Foo {
    $apiKey = $env::apiKey();

    return new Foo($apiKey, $debug);
}
php
<?php
declare(strict_types=1);

// file: /app/src/Helpers/Env.php

namespace App\Helpers;

use function getenv;

class Env
{
    // …

    public static function apiKey(): string
    {
        $apiKey = match (getenv('APP_ENV')) {
            'dev' => getenv('APP_API_KEY_LOCAL'),
            'staging' => getenv('APP_API_KEY_STAGING'),
            'prod' => getenv('APP_API_KEY_PROD'),
        };
        
        // $apiKey calculation
        
        return $apiKey;
    }
}

In the callable_as_is.php configuration file, you need to declare three container identifiers:

  • 'services.foo_from_anonymous_fn' – an anonymous function.
  • 'services.foo_from_static_method' – a static class method.
  • 'services.foo_from_function' – a function.

When accessed using these identifiers, the container's get() method should return an instance of the PHP class \App\Services\Foo with different values for the $apiKey and $debug properties.

php
<?php
declare(strict_types=1);

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

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

use Kaspi\DiContainer\DiContainerBuilder;

putenv('APP_ENV=dev');
putenv('APP_API_KEY_LOCAL=FOO-BAR');
putenv('APP_API_KEY_STAGING=BAR-BAZ');
putenv('APP_API_KEY_PROD=BAZ-QUX');

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

$fooFromFn = $container->get('services.foo_from_anonymous_fn');
var_dump($fooFromFn);

$fooFromStaticMethod = $container->get('services.foo_from_static_method');
var_dump($fooFromStaticMethod);

$fooFromFunction = $container->get('services.foo_from_function');
var_dump($fooFromStaticMethod);
php
<?php
declare(strict_types=1);

// file: /app/config/callable_as_is.php

use App\Services\Foo;

return static function (): Generator {
   yield 'services.foo_from_anonymous_fn' => static fn () => new Foo(
        apiKey: 'qwerty-value',
        debug: false
    );

   yield 'services.foo_from_static_method' => [ServiceFoo::class, 'makeForLocal'];
   
   yield 'services.foo_from_function' => 'App\Functions\staging_service';
};

Run the following command in the terminal:

shell
php /app/src/container.php

A message like the following will appear:

console
object(App\Services\Foo)#1 (2) {
  ["apiKey"]=>
  string(12) "qwerty-value"
  ["debug"]=>
  bool(false)
}

object(App\Services\Foo)#1 (2) {
  ["apiKey"]=>
  string(7) "FOO-BAR"
  ["debug"]=>
  bool(true)
}

object(App\Services\Foo)#1 (2) {
  ["apiKey"]=>
  string(7) "FOO-BAR"
  ["debug"]=>
  bool(false)
}

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

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