PHP code example of kaspi / di-container

1. Go to this page and download the library: Download kaspi/di-container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kaspi / di-container example snippets


namespace App\Services;

// Класс для создания сообщения
class Envelope {
    public function subject(string $subject): static {
        // ...
        return $this;
    }
    
    public function message(string $message): static {
        // ...
        return $this;
    }
}

// Сервис отправки почты
class Mail {
    public function __construct(private Envelope $envelope) {}
    
    public function envelop(): Envelope {
        return $this->envelope;
    }
    
    public function send(): bool {
        // отправка сообщения 
    }
}

namespace App\Models;
// Модель данных — пост в блоге.
class Post {
    public string $title;
    // ...
}

namespace App\Controllers;

use App\Services\Mail;
use App\Models\Post;

// Контроллер для обработки действия.
class  PostController {
    public function __construct(private Mail $mail) {}
    
    public function send(Post $post): bool {
        $this->mail->envelop()
            ->subject('Publication success')
            ->message('Post <'.$post->title.'> was published.');
        return $this->mail->send();
    }
}

// Создать контейнер.
$container = (new Kaspi\DiContainer\DiContainerFactory())->make();

// more code...

//Заполняем модель данными.
$post = new App\Models\Post();
$post->title = 'Publication about DiContainer';

// получить класс PostController с внедренным сервисом Mail и выполнить метод "send"
$postController = $container->get(App\Controllers\PostController::class);
$postController->send($post);

$post = new App\Controllers\PostController(
    new App\Services\Mail(
        new App\Services\Envelope()
    )
);

$post = new App\Models\Post();
$post->title = 'Publication about DiContainer';

// ...

// получить класс PostController с внедренным сервисом Mail и выполнить метод "send"
$container->call(
    definition: [App\Controllers\PostController::class, 'send'],
    arguments: ['post' => $post]
);


use Kaspi\DiContainer\{DiContainerConfig, DiContainer};

$diConfig = new DiContainerConfig(
    // Ненужно объявлять каждую зависимость.
    // Если класс, функция или интерфейс существуют
    // и может быть запрошен через автозагрузку (например через composer),
    // то объявлять каждое определение необязательно.
    useZeroConfigurationDefinition: true,
    // Использовать Php-атрибуты для объявления определений контейнера.
    useAttribute: true,
    // Сервис (объект) создавать как одиночку (singleton pattern).
    isSingletonServiceDefault: false,
);
// передать настройки в контейнер
$container = new DiContainer(config: $diConfig);

use Kaspi\DiContainer\DiContainerFactory;

$container = (new DiContainerFactory())->make(definitions: []);

use Kaspi\DiContainer\DiContainerFactory;

function testFunc(\Psr\Container\ContainerInterface $c) {
    return $c;
}

$container = (new DiContainerFactory())->make();
$container->call('testFunc') instanceof DiContainer; // true

use Kaspi\DiContainer\DiContainerFactory;
use Psr\Container\ContainerInterface;

class TestClass {
    public function __construct(
        public ContainerInterface $container
    ) {}
}

$container = (new DiContainerFactory())->make();
$container->get(TestClass::class)->container instanceof DiContainer; // true
shell
docker-compose run --rm php composer install
shell
docker-compose run --rm php vendor/bin/phpunit --no-coverage
shell
docker-compose run --rm php vendor/bin/phpunit
shell
docker-compose run --rm php vendor/bin/phpstan
shell
docker-compose run --rm php sh