PHP code example of phpsoftbox / container

1. Go to this page and download the library: Download phpsoftbox/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/ */

    

phpsoftbox / container example snippets




use PhpSoftBox\Container\ContainerBuilder;
use Psr\Container\ContainerInterface;
use function PhpSoftBox\Container\autowire;
use function PhpSoftBox\Container\factory;
use function PhpSoftBox\Container\get;

$builder = new ContainerBuilder();
$builder->useAutowiring(true);
$builder->addDefinitions([
    LoggerInterface::class => autowire(Logger::class),
    UserService::class => factory(
        static fn (ContainerInterface $c): UserService => new UserService($c->get(LoggerInterface::class)),
    ),
    UserServiceInterface::class => get(UserService::class),
]);
$builder->lazy(UserService::class);

$container = $builder->build();

$builder->enableCompilation(__DIR__ . '/var/cache/di');
$container = $builder->build();

$container = $builder->warmup();

ContainerBuilder::clearCompiledCache(__DIR__ . '/var/cache/di'); // int — количество удалённых файлов

use PhpSoftBox\Container\Reset\ServicesResetter;

$resetter = new ServicesResetter($container, [
    // Классы из пакетов, которые не зависят от контейнера: запись → метод (или список методов).
    ConnectionManagerInterface::class => 'clearWarmup',
    EntityManagerInterface::class     => 'clear',
]);

$resetter->reset();



namespace PHPSTORM_META
{
    override(\Psr\Container\ContainerInterface::get(0), map([
        '' => '@',
    ]));

    override(\PhpSoftBox\Container\Container::get(0), map([
        '' => '@',
    ]));

    override(\PhpSoftBox\Container\Container::make(0), map([
        '' => '@',
    ]));

    override(\PhpSoftBox\Container\FactoryInterface::make(0), map([
        '' => '@',
    ]));
}

$logger = $container->get(LoggerInterface::class); // LoggerInterface
$service = $container->make(UserService::class); // UserService