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


// src/Services/Envelope.php
namespace App\Services;

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

// src/Services/Mail.php
namespace App\Services;

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

// src/Models/Post.php
namespace App\Models;

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

// src/Controllers/PostController.php
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();
    }
}

use App\Controllers\PostController;
use App\Models\Post;
use Kaspi\DiContainer\DiContainerFactory;

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

// more code...

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

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

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

use App\Controllers\PostController;
use App\Models\Post;

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

// ...

// получить класс PostController с внедренным сервисом Mail и выполнить метод "send"
$container->call(
    definition: [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();

DiContainerFactory::__construct(
    ?Kaspi\DiContainer\Interfaces\DiContainerConfigInterface $config = null
)

DiContainerFactory::make(
    iterable $definitions = []
): \Kaspi\DiContainer\Interfaces\DiContainerInterface

> use Kaspi\DiContainer\DiContainerFactory;
>
> function testFunc(\Psr\Container\ContainerInterface $c) {
>     return $c;
> }
>
> $container = (new DiContainerFactory())->make();
>
> var_dump($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();
>
> var_dump($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