PHPackages                             aolbrich/php-di-container - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. aolbrich/php-di-container

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

aolbrich/php-di-container
=========================

PHP Dependency Injection cotainer

v1.0.8(3y ago)0391MITPHPPHP &gt;=8.0.0

Since Mar 9Pushed 3y ago1 watchersCompare

[ Source](https://github.com/olbrichattila/php-di-container)[ Packagist](https://packagist.org/packages/aolbrich/php-di-container)[ RSS](/packages/aolbrich-php-di-container/feed)WikiDiscussions main Synced today

READMEChangelog (9)Dependencies (4)Versions (10)Used By (1)

Constructor Dependency Injection container
==========================================

[](#constructor-dependency-injection-container)

This class implements a simple constructor dependency injection container
-------------------------------------------------------------------------

[](#this-class-implements-a-simple-constructor-dependency-injection-container)

Installation:
-------------

[](#installation)

```
composer require aolbrich/php-di-container

```

### Basic Usage:

[](#basic-usage)

If the class constructor implements a callable class then it will be auto wired, no mapping required. For example:

```
class ExampleClass
{
    public function __construct(private readonly ExampleClass $exampleClass) {}

    ...
}

```

### Implementation:

[](#implementation)

```
use Aolbrich\PhpDiContainer\Container;

// Create new container
$container = new Container();

// Resolve class
$class = $container->get(ExampleClass::class);

```

Returns new class and autowire all methods where the annotation says @atowire
-----------------------------------------------------------------------------

[](#returns-new-class-and-autowire-all-methods-where-the-annotation-says-atowire)

(Note: The new class will not return with the same class name, or not even inherited from the original class)

```
$container = new Container();
$container->set(ExampleServiceInterface::class, ExampleService::class);

$class = $container->resolveClass(ExampleClassForFunctionLevelResolve::class);

echo $class->getResponseWithAutowiredParams(); // they will be auto wired

```

Using array to set the resolver definitions
-------------------------------------------

[](#using-array-to-set-the-resolver-definitions)

It is also possible to pass the definitions to the class via it's constructor, or calling the setDefinitions method instad of using the `set` method. It makes possible to set multiple definitions at one:

Example:

```
$definitions = [
    ExampleServiceInterface::class => ExampleService::class,
];

$container = new Container($definitions);

```

OR

```
$definitions = [
    ExampleServiceInterface::class => ExampleService::class,
];

$container = new Container();
$container->setDefinitions($definitions);

```

The class:
----------

[](#the-class)

```
class ExampleClassForFunctionLevelResolve
{
    /**
     * @Autowire
     */
    public function getResponseWithAutowiredParams(
        ExampleServiceInterface $exampleService,
        ExampleSubService $exampleSubService): string
    {
        return
            $exampleService->getResponse() . ' / ' .
            $exampleSubService->getResponse() . PHP_EOL;
    }
}

```

### Usage with interface resolution:

[](#usage-with-interface-resolution)

If the class implements a constuctor injection with interface type hint, then the container cannot resolve the depenceny automatically, therefore mapping should be provided by the set method. Mapping can be done by interface and class names, or interface name and closure as well.

The following two example illustrate those solutions:

```
class ExampleClass
{
    public function __construct(private readonly ExampleInterface $example) {}

    ...
}

```

### Implementation:

[](#implementation-1)

```
use Aolbrich\PhpDiContainer\Container;

// Create new container
$container = new Container();

// Configure what to resolve
$container->set(
    ExampleInterface::class,
    ExampleClass::class
);
$class = $container->get(ExampleClass::class);

```

### Same implementation using closure:

[](#same-implementation-using-closure)

```
use Aolbrich\PhpDiContainer\Container;

// Create new container
$container = new Container();

// Configure what to resolve
$container->set(ExampleServiceInterface::class, function(Container $container) {
    return $container->get(ExampleService::class);
});

$class = $container->get(ExampleClass::class);

```

Setter Autowire
---------------

[](#setter-autowire)

It is also possible to auto wire setters, The requirement for auto wiring setters are:

- The method have to be public
- The method name have to start with "set" like "setLogger()"
- To auto wire, you need to add the @autowire annotations.

There can be any amount of setters

Example class wiring two dependencies at one setter.

```
class ExampleSetterAutowireClass
{
    private ExampleServiceInterface $exampleService;
    private ExampleSubService $exampleSubService;

    /**
     * @Autowire
     */
    public function setAutowire(
        ExampleServiceInterface $exampleService,
        ExampleSubService $exampleSubService
    ) {
        $this->exampleService =  $exampleService;
        $this->exampleSubService = $exampleSubService;
    }

    public function getResponse(): string
    {
        return
            $this->exampleService->getResponse() . ' / ' .
            $this->exampleSubService->getResponse() . PHP_EOL;
    }
}

```

### Add primitive parameters

[](#add-primitive-parameters)

You can add extra parameters to your class resolve to bind:

Examlpe:

```
$class = $container->get(ExampleParameterBinding::class, [
    'intValue' => 10,
    'stringValue' => "Hello String",
    'anyValue' => "This is any value"
]);
echo $class->getResponse();

```

Class implementation:

```
class ExampleParameterBinding
{
    private mixed $anyValue;

    public function __construct(
        private readonly ExampleServiceInterface $exampleService,
        private readonly ExampleSubService $exampleSubService,
        private readonly int $intValue,
        private readonly string $stringValue,
        $anyValue,
    ) {
        $this->anyValue = $anyValue;
    }

    public function getResponse(): string
    {
        return
            $this->intValue . ' / ' .
            $this->stringValue . ' / ' .
            $this->anyValue . ' / ' .
            $this->exampleService->getResponse() . ' / ' .
            $this->exampleSubService->getResponse() . PHP_EOL;
    }
}

```

### Singleton creation support

[](#singleton-creation-support)

Class can be created as signletor by using the sigleton() function or auto wire with closure. Examples:

```
$container = new Container();

// Resolve as non singleton
$class = $container->get(ExampleSetterAutowireClass::class);
$class2 = $container->get(ExampleSetterAutowireClass::class);

echo $class === $class2 ? "Same class instance created\n" : "Different class instance created\n";

// Resolve as singleton
$class = $container->singleton(ExampleSetterAutowireClass::class);
$class2 = $container->singleton(ExampleSetterAutowireClass::class);

echo $class === $class2 ? "Same class instance created\n" : "Different class instance created\n";

// Autowire as Singleton
$container->set(ExampleService::class, function(Container $container) {
    return $container->singleton(ExampleService::class);
});

$class = $container->get(ExampleService::class);
$class2 = $container->get(ExampleService::class);

echo $class === $class2 ? "Same class instance created\n" : "Different class instance created\n";

```

### Run the unit test

[](#run-the-unit-test)

```
./vendor/bin/phpunit test

```

Tools
-----

[](#tools)

Run code quality check:

```
./vendor/bin/phpstan analyse src test
./vendor/bin/psalm --show-info=true

```

Note
----

[](#note)

This is not a full implementation of a dependency injection container. It resolves only constructor dependencies.

Features missing / will be added

- Constructor Injection
- Setter Injection
- Method Injection
- Singleton support
- Property Injection (it will not be done, as it does not considered as a goop practice any more)
- Injecting primitive paramater values
- Caching
- Aliases
- Annotations (partly implemented with @autowire keywords in setters)
- Immutable-setter Injection
- Only basic circular reference check added, improve to check for example, if ClassA depends on ClassB, and ClassB depends on ClassC, which in turn depends on ClassA, the code would not detect this circular reference. This can be addressed by maintaining a stack of dependencies and checking for cycles in the stack.

Licence
-------

[](#licence)

MIT licence

###  Health Score

25

—

LowBetter than 35% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

9

Last Release

1200d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/437a41d4417cd7909313efcbe53b4c148c68c7ae2b5204f2ecad044b94e10bd8?d=identicon)[olbrichattila](/maintainers/olbrichattila)

---

Top Contributors

[![olbrichattila](https://avatars.githubusercontent.com/u/12551116?v=4)](https://github.com/olbrichattila "olbrichattila (25 commits)")

---

Tags

dependenciesdependency-injectionphp-librarydependency-injection

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/aolbrich-php-di-container/health.svg)

```
[![Health](https://phpackages.com/badges/aolbrich-php-di-container/health.svg)](https://phpackages.com/packages/aolbrich-php-di-container)
```

###  Alternatives

[symfony/dependency-injection

Allows you to standardize and centralize the way objects are constructed in your application

4.2k455.6M9.5k](/packages/symfony-dependency-injection)[illuminate/contracts

The Illuminate Contracts package.

706130.3M13.2k](/packages/illuminate-contracts)[illuminate/container

The Illuminate Container package.

31182.0M2.4k](/packages/illuminate-container)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

564576.7k49](/packages/ecotone-ecotone)[symfony/type-info

Extracts PHP types information.

20069.8M269](/packages/symfony-type-info)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k41](/packages/civicrm-civicrm-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
