Small Dependency Injection – DEV Community


I’ve just released small/dependency-injection — a lightweight, framework-agnostic Dependency Injection container for PHP 8.4.




Quick Start

Install via Composer:

composer require small/dependency-injection
Enter fullscreen mode

Exit fullscreen mode

Define your container configuration:



use Small\DependencyInjection\AbstractContainerConfiguration;
use function Small\DependencyInjection\injectService;
use function Small\DependencyInjection\injectParameter;

class AppConfig extends AbstractContainerConfiguration
{
    public function configure(): self
    {
        $this->parameter('secret', 'top-secret')
             ->service(
                 MyServiceInterface::class,
                 MyService::class,
                 [
                     injectParameter('secret'),
                     injectService(LoggerInterface::class),
                 ]
             )
             ->autowireNamespace('App');

        return $this;
    }
}
Enter fullscreen mode

Exit fullscreen mode

Use it:

$config = new AppConfig(__DIR__ . '/composer.json');
$config->loadParameters($container);

$myService = $container->get(MyServiceInterface::class);
Enter fullscreen mode

Exit fullscreen mode




Links


That’s it — a simple, modern DI container for your next PHP project.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *