small/dependency-injection

Dependency injection library

0.1.0 2025-09-27 19:41 UTC

This package is not auto-updated.

Last update: 2025-09-27 20:07:58 UTC


README

small/dependency-injection

    

A lightweight Dependency Injection Container for PHP 8.4 with autowiring, environment/parameter injection, and service definition validation.

Features

  • Service definitions with explicit parameters
  • Injection helpers:
    • injectService() – inject another service
    • injectParameter() – inject a container parameter
    • injectEnv() – inject an environment variable
    • injectConstant() – inject a PHP constant
  • Autowiring support:
    • Automatically resolves constructor dependencies for classes in configured namespaces
    • Validates against constructor signatures via reflection
  • Error safety:
    • Detects missing/invalid parameters
    • Type-checks against PHP type hints (including union & intersection types)
  • PHP 8.4 property hooks used for immutability of service definitions

Installation

composer require small/dependency-injection

If you are testing locally without Packagist:

git clone https://git.small-project.dev/lib/small-depency-injection.git
cd small-dependency-injection
composer install

Quick Start

<?php

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

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

// bootstrap
$config = new MyConfig(__DIR__ . '/composer.json');
$container = new Container(
    $loader = new ServiceLoader($config->getServiceDefinitions())
);
$myService = $container->get(MyServiceInterface::class);

Running Tests

We use Pest for tests:

composer install
composer unit-tests

License

Copyright 2025 - Sébastien Kus
Under the GNU GPL V3 license.