Skip to content

Declaring an object in a runtime container ​

In certain container usage scenarios, a situation may arise where it is necessary to inject a PHP class as a dependency, yet the configuration for this class is not known in advance meaning that at the time of configuration, only the container identifier[1] or the fully qualified class name.

The actual state of the object (the PHP class instance) is initialized outside the container and injected into the container only at runtime, using a pre-defined container identifier or the class's FQCN[2].

Within the context of a dependency container, such a PHP class is referred to as a Runtime Definition.

During container compilation, parameters that depend on a Runtime Definition must be aware of the existence of a PHP class that will only be injected into the dependency container at runtime.

You can create a definition within the Runtime Definition container using the diRuntime() helper function or the \Kaspi\DiContainer\Attributes\DiRuntime attribute.

IMPORTANT

Declaring an item within the Runtime Definition container configuration does not create a PHP class configuration; it merely provides a container identifier[1:1].

Example of implementing a runtime definition ​

PHP classes:

php
<?php
declare(strict_types=1);

// file: /app/src/Core/Kernel.php

namespace App\Core;

use Kaspi\DiContainer\Interfaces\DiContainerInterface;
use App\Services\Qux;

class Kernel
{
    public function __construct(
        private readonly DiContainerInterface $container
    ) {}

    // ...

    public function initKernel(): void
    {
        // ...

        $this->container->set($this::class, $this);
        
        $secureString = \calculate_secure_string();
        $qux = new Qux($secureString);
        
        $this->container->set($qux::class, $qux);
    }
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Qux
{
    public function __construct(
        private readonly string $secureString
    ) {}

    // …    
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

use App\Core\Kernel;

final class Bar
{
    public function __construct(
        public readonly Kernel $kernel,
        public readonly string $baz,
    ) {}    
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

final class Foo
{
    public function __construct(
        public readonly Qux $qux,
        public readonly string $baz,
    ) {}    
}

The actual state of the PHP classes \App\Core\Kernel and \App\Services\Qux can only be determined outside the scope of the container configuration; however, the project contains other PHP classes specifically \App\Services\Bar and \App\Services\Foo that inject these classes as constructor dependencies.

Container compilation is required during the build process, which necessitates declaring both \App\Core\Kernel and \App\Services\Qux within the dependency container as Runtime Definitions.

Declaration in configuration files ​

In the runtime_services.php configuration file, the PHP classes \App\Core\Kernel and \App\Services\Qux are declared using the helper function diRuntime().

We will declare the PHP classes \App\Services\Bar and \App\Services\Foo, along with their scalar dependencies, in the services.php configuration file; the container will automatically inject the type-hinted dependencies[3] based on its configuration.

To declare scalar dependencies, we use container parameters.

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\{Bar, Foo};

$container = (new DiContainerBuilder())
    ->loadParameters('/app/config/params.php')
    ->load('/app/config/runtime_services.php')
    ->load('/app/config/services.php')
    ->compileToFile('/app/var', 'App\Core\Container')
    ->build();


// …

/*
 * The \App\Core\Kernel::initKernel() method
 * will set the actual values for the Runtime Definition.
 */ 
$kernel = new \App\Core\Kernel($container);
$kernel->initKernel();

// …

$bar = $container->get(Bar::class);
var_dump($bar->kernel, $bar->baz);

echo PHP_EOL;

$foo = $container->get(Foo::class);
var_dump($qux->qux, $foo->baz);
php
<?php
declare(strict_types=1);

// file: /app/config/runtime_services.php

use App\Core\Kernel;
use App\Services\Qux;

use function Kaspi\DiContainer\diRuntime;

return static function (): Generator {
    yield diRuntime(Kernel::class);
    
    yield diRuntime(Qux::class);
};
php
<?php
declare(strict_types=1);

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

use App\Services\{Foo, Bar};

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

return static function (): Generator {
    yield diAutowire(Foo::class)
        ->bindArguments(
            baz: diParameter('app.baz_value')
        );
    
    yield diAutowire(Bar::class)
        ->bindArguments(
            baz: diParameter('app.baz_value')
        );
};
php
<?php
declare(strict_types=1);

// file: /app/config/params.php


return static function (): Generator {
    yield 'app.baz_value' => 'Lorem ipsum';
}

Run the following command in the terminal:

shell
php /app/src/container_build.php

A message like the following will appear:

console
object(App\Core\Kernel)#2 (0) {
}
string(11) "Lorem ipsum"

object(App\Services\Qux)#4 (0) {
}
string(11) "Lorem ipsum"

Declaration via attributes ​

Declare PHP classes \App\Core\Kernel and \App\Services\Qux via the attribute \Kaspi\DiContainer\Attributes\DiRuntime.

Declare scalar dependencies in the PHP classes \App\Services\Bar and \App\Services\Foo using the \Kaspi\DiContainer\Attributes\Parameter attribute; the container will automatically resolve typed dependencies[3:1] in these classes based on its configuration.

PHP classes:

php
<?php
declare(strict_types=1);

// file: /app/src/Core/Kernel.php

namespace App\Core;

use Kaspi\DiContainer\Attributes\DiRuntime;
use Kaspi\DiContainer\Interfaces\DiContainerInterface;
use App\Services\Qux;

#[DiRuntime]
class Kernel
{
// …
php
<?php
declare(strict_types=1);

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

namespace App\Services;

use Kaspi\DiContainer\Attributes\DiRuntime;

#[DiRuntime]
final class Qux
{
// …
php
<?php
declare(strict_types=1);

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

namespace App\Services;

use App\Core\Kernel;
use Kaspi\DiContainer\Attributes\Parameter;

final class Bar
{
    public function __construct(
        public readonly Kernel $kernel,
        #[Parameter('app.baz_value')]
        public readonly string $baz,
    ) {}    
}
php
<?php
declare(strict_types=1);

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

namespace App\Services;

use Kaspi\DiContainer\Attributes\Parameter;

final class Foo
{
    public function __construct(
        public readonly Qux $qux,
        #[Parameter('app.baz_value')]
        public readonly string $baz,
    ) {}    
}
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\{Bar, Foo};

$container = (new DiContainerBuilder())
    ->loadParameters('/app/config/params.php')
    ->import(namespace: 'App\\', src: '/app/src')
    ->compileToFile('/app/var', 'App\Core\Container')
    ->build();

// …

/*
 * Метод \App\Core\Kernel::initKernel()
 * установит реальные значения для Runtime Definition.
 */ 
$kernel = new \App\Core\Kernel($container);
$kernel->initKernel();

// …

$bar = $container->get(Bar::class);
var_dump($bar->kernel, $bar->baz);

echo PHP_EOL;

$foo = $container->get(Foo::class);
var_dump($qux->qux, $foo->baz);
php
<?php
declare(strict_types=1);

// file: /app/config/params.php


return static function (): Generator {
    yield 'app.baz_value' => 'Lorem ipsum';
}

Run the following command in the terminal:

shell
php /app/src/container_build.php

A message like the following will appear:

console
object(App\Core\Kernel)#2 (0) {
}
string(11) "Lorem ipsum"

object(App\Services\Qux)#4 (0) {
}
string(11) "Lorem ipsum"

  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. Fully Qualified Class Name – the full name of a class or interface, including its namespace. ↩︎

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