PHPackages                             initphp/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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. initphp/container

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

initphp/container
=================

Minimal PSR-11 dependency injection container with reflection-based autowiring.

1.0.0(1mo ago)11081MITPHPPHP ^8.1CI passing

Since Jun 28Pushed 3w ago1 watchersCompare

[ Source](https://github.com/InitPHP/Container)[ Packagist](https://packagist.org/packages/initphp/container)[ RSS](/packages/initphp-container/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (5)Versions (6)Used By (1)

InitPHP Container
=================

[](#initphp-container)

Minimal [PSR-11](https://www.php-fig.org/psr/psr-11/) dependency injection container with reflection-based autowiring.

[![Latest Stable Version](https://camo.githubusercontent.com/3b640c777b119ac306e315d3f93d939399c2bfd928be18b32a42351c78ecb932/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f636f6e7461696e65722f762f737461626c65)](https://packagist.org/packages/initphp/container)[![Total Downloads](https://camo.githubusercontent.com/c22b4b21887355339119ec631cbb4a9d8a78d4b00e96039fa43895cc534e7bb3/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f636f6e7461696e65722f646f776e6c6f616473)](https://packagist.org/packages/initphp/container)[![License](https://camo.githubusercontent.com/c7ee936ac4148f5dd7e67781ab053eb7c1379c74158462c2c554f65934c57a7c/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f636f6e7461696e65722f6c6963656e7365)](https://packagist.org/packages/initphp/container)[![PHP Version Require](https://camo.githubusercontent.com/a584ec5c5ac08ec11fe909fe2fd13a9ab62bd8ea5cdbb5fd876d1f1d163b2388/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f636f6e7461696e65722f726571756972652f706870)](https://packagist.org/packages/initphp/container)

The container resolves entries lazily. You can register values, factories and class bindings explicitly, or let the container autowire a class straight from its name by reading its constructor signature through reflection. Every resolved entry is cached, so the container behaves as a shared (singleton) registry.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- [`psr/container`](https://packagist.org/packages/psr/container) `^2.0`

Installation
------------

[](#installation)

```
composer require initphp/container
```

Quick Start
-----------

[](#quick-start)

```
require_once 'vendor/autoload.php';

use InitPHP\Container\Container;

class Mailer
{
}

class UserService
{
    public function __construct(public Mailer $mailer)
    {
    }
}

$container = new Container();

// No registration needed: the container reads UserService's constructor,
// builds the Mailer dependency automatically and injects it.
$service = $container->get(UserService::class);

var_dump($service instanceof UserService); // bool(true)
var_dump($service->mailer instanceof Mailer); // bool(true)
```

Usage
-----

[](#usage)

### Autowiring

[](#autowiring)

When you call `get()` with an existing class name, the container instantiates it and recursively resolves every class-typed constructor argument:

```
$service = $container->get(UserService::class);
```

The resolved instance is cached. Asking for the same identifier again returns the exact same object:

```
$container->get(Mailer::class) === $container->get(Mailer::class); // true
```

### Storing values

[](#storing-values)

`set()` accepts any value. Scalars, arrays and objects are returned as they were stored:

```
$container->set('app.name', 'InitPHP');
$container->set('config', ['debug' => true]);
$container->set('logger', new FileLogger('/var/log/app.log'));

$container->get('app.name'); // 'InitPHP'
$container->get('config');   // ['debug' => true]
$container->get('logger');   // the same FileLogger instance
```

### Factories (closures)

[](#factories-closures)

Register a `Closure` to build an entry lazily. The closure receives the container and runs only once, the first time the entry is requested:

```
use Psr\Container\ContainerInterface;

$container->set('pdo', function (ContainerInterface $c) {
    return new PDO('sqlite::memory:');
});

$pdo = $container->get('pdo'); // closure runs here, result is cached
```

### Binding interfaces to implementations

[](#binding-interfaces-to-implementations)

Bind an interface (or any identifier) to a concrete class name so that both direct lookups and autowired dependencies resolve to the implementation:

```
interface LoggerInterface
{
}

class FileLogger implements LoggerInterface
{
}

class Report
{
    public function __construct(public LoggerInterface $logger)
    {
    }
}

$container->set(LoggerInterface::class, FileLogger::class);

$container->get(LoggerInterface::class);      // FileLogger instance
$container->get(Report::class)->logger;       // the same FileLogger instance
```

### Checking for an entry

[](#checking-for-an-entry)

`has()` returns `true` when `get()` would not throw a `NotFoundException` — that is, the identifier is a registered entry or an existing class name:

```
$container->has('app.name');         // true after set()
$container->has(UserService::class); // true (autowirable class)
$container->has('missing');          // false
```

How resolution works
--------------------

[](#how-resolution-works)

`get($id)` resolves in this order:

1. Return the cached instance if `$id` was resolved before.
2. If `$id` was registered with `set()`, build it (invoke the closure, instantiate the class name, or return the stored value) and cache it.
3. If `$id` is an existing class name, autowire it and cache it.
4. Otherwise throw `NotFoundException`.

Constructor parameters are resolved as follows: a class-typed parameter is fetched from the container; otherwise its default value is used; otherwise `null` is supplied for nullable parameters. If none of these apply, resolution fails.

Exceptions
----------

[](#exceptions)

All exceptions live in `InitPHP\Container\Exception` and implement the relevant PSR-11 interface.

ExceptionImplementsThrown when`NotFoundException``Psr\Container\NotFoundExceptionInterface`The identifier is neither registered nor an existing class.`DependencyIsNotInstantiableException``Psr\Container\ContainerExceptionInterface`The target is an interface, abstract class, or has a non-public constructor.`DependencyHasNoDefaultValueException``Psr\Container\ContainerExceptionInterface`A constructor parameter cannot be autowired and has no default or nullable fallback.`CircularDependencyException``Psr\Container\ContainerExceptionInterface`A class depends on itself directly or through a cycle.`ContainerException` is the base class for `NotFoundException` and the three resolution exceptions, so you can catch every container error with a single `catch (ContainerException $e)`.

Documentation
-------------

[](#documentation)

In-depth guides with runnable examples live in the [`docs/`](./docs) directory:

- [Getting Started](./docs/getting-started.md)
- [Autowiring](./docs/autowiring.md)
- [Binding &amp; Factories](./docs/binding-and-factories.md)
- [Exceptions &amp; Error Handling](./docs/exceptions.md)
- [Limitations](./docs/limitations.md)

Testing
-------

[](#testing)

```
composer test      # PHPUnit
composer stan      # PHPStan (max level)
composer cs-check  # PHP-CS-Fixer (dry run)
```

Contributing
------------

[](#contributing)

Contributions are welcome. Please read the org-wide [CONTRIBUTING guide](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) before opening a pull request.

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) &lt;&gt;

License
-------

[](#license)

Released under the [MIT License](./LICENSE).

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance94

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity61

Established project with proven stability

 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 ~361 days

Total

5

Last Release

22d ago

Major Versions

0.4 → 1.0.02026-05-29

PHP version history (2 changes)0.2PHP &gt;=7.4

1.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b6b34f3ac8938d8ee52ba3bd260680855dc5715c7b2929d9380de30d15a67dd?d=identicon)[muhammetsafak](/maintainers/muhammetsafak)

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (8 commits)")

---

Tags

autowiringcontainerdependency-injectiondependency-injection-containerdi-containerinitphpioc-containerphpphp8psrpsr-11reflectionservice-containercontainerPSR-11Autowiringdependency-injectiondiioc

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/initphp-container/health.svg)

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

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.9k55.5M1.2k](/packages/php-di-php-di)[slince/di

A flexible dependency injection container

20272.1k6](/packages/slince-di)

PHPackages © 2026

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