PHPackages                             miladrahimi/phpcontainer - 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. miladrahimi/phpcontainer

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

miladrahimi/phpcontainer
========================

Dependency injection (IoC) container for PHP projects

v5.3.3(2y ago)1324.1k↑50.6%12MITPHPPHP &gt;=7.4

Since Jul 28Pushed 2y ago3 watchersCompare

[ Source](https://github.com/miladrahimi/phpcontainer)[ Packagist](https://packagist.org/packages/miladrahimi/phpcontainer)[ Docs](https://github.io/miladrahimi/phpcontainer)[ Fund](https://miladrahimi.com/pay.html)[ Fund](https://www.paypal.com/paypalme/realmiladrahimi)[ RSS](/packages/miladrahimi-phpcontainer/feed)WikiDiscussions master Synced yesterday

READMEChangelog (10)Dependencies (2)Versions (21)Used By (2)

[![Latest Stable Version](https://camo.githubusercontent.com/7eebbc6e1572dce35330bb0faa1c7f0bccb5e95e1aed619c3556512226d828fb/68747470733a2f2f706f7365722e707567782e6f72672f6d696c6164726168696d692f706870636f6e7461696e65722f76)](//packagist.org/packages/miladrahimi/phpcontainer)[![Total Downloads](https://camo.githubusercontent.com/0fcb1aea2be63ea813de3d300514a2181fe3db5cbb2c0d68569d3c04b973b776/68747470733a2f2f706f7365722e707567782e6f72672f6d696c6164726168696d692f706870636f6e7461696e65722f646f776e6c6f616473)](//packagist.org/packages/miladrahimi/phpcontainer)[![Build](https://github.com/miladrahimi/phpcontainer/actions/workflows/ci.yml/badge.svg)](https://github.com/miladrahimi/phpcontainer/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/7cec0ebdb6a9a1188675ae8651da717657fcd8b23c731cbf8967307ed03a6c1e/68747470733a2f2f636f6465636f762e696f2f67682f6d696c6164726168696d692f706870636f6e7461696e65722f67726170682f62616467652e7376673f746f6b656e3d4c465730483047534d51)](https://codecov.io/gh/miladrahimi/phpcontainer)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/36c2d951488faff0b6c81f957df560efe2cf179efb1cee0e2cf49c69c2f1181b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d696c6164726168696d692f706870636f6e7461696e65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/miladrahimi/phpcontainer/?branch=master)[![License](https://camo.githubusercontent.com/f745407d63607648cef55f90ceb73ff07575c2ae09090a49ed5c23ce8f1ace5d/68747470733a2f2f706f7365722e707567782e6f72672f6d696c6164726168696d692f706870636f6e7461696e65722f6c6963656e7365)](//packagist.org/packages/miladrahimi/phpcontainer)

PhpContainer
============

[](#phpcontainer)

A dependency injection (Inversion of Control) container written in PHP programming language, compliant with PSR-11 standards.

Features:

- Singleton, transient, and closure bindings
- Explicit and implicit bindings
- Typed and named bindings
- Automatic injection

Overview
--------

[](#overview)

[Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle) is a fundamental concept in Object-oriented design.

It leads to important ideas like [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection), [Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control), and the creation of an [IoC Container](http://www.codeproject.com/Articles/542752/Dependency-Inversion-Principle-IoC-Container-Depen).

For PHP projects, there's the PhpContainer, a handy tool that provides a dependency injection container (IoC Container) conforming to [PSR-11 standards](https://www.php-fig.org/psr/psr-11).

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

[](#installation)

To integrate PhpContainer into your project, use the following Composer command:

```
composer require miladrahimi/phpcontainer:5.*
```

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

[](#documentation)

### Explicit Binding

[](#explicit-binding)

Explicit binding involves directly linking an abstraction to a concrete implementation. This binding can be achieved by using the `singleton()`, `transient()`, and `closure()` methods.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();

$container->singleton(DatabaseInterface::class, MySQL::class);
$container->transient(MailerInterface::class, MailTrap::class);
$container->closure('sum', function($a, $b) { return $a + $b; });

$database = $container->get(DatabaseInterface::class); // An instance of MySQL
$mailer = $container->get(MailerInterface::class); // An instance of MailTrap
$sum = $container->get('sum'); // A closure: $sum(6, 7) => 13
```

#### Binding Methods

[](#binding-methods)

- Singleton binding: The container creates the concrete only once and returns it whenever needed.
- Transient binding: The container clones or creates brand-new concrete each time you need it.
- Closure binding: Only for closures. It prevents the container from calling the closure (the default behavior).

The following example demonstrates the differences between singleton and transient binding.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();

$container->transient(InterfaceA::class, ClassA::class);
$container->singleton(InterfaceB::class, ClassB::class);

$a1 = $container->get(InterfaceA::class);
$a1->name = 'Something';

$a2 = $container->get(InterfaceA::class);
echo $a2->name; // NULL

$b1 = $container->get(InterfaceB::class);
$b1->name = 'Something';

$b2 = $container->get(InterfaceB::class);
echo $b2->name; // 'Something'
```

### Implicit Binding

[](#implicit-binding)

When the container needs a class without a specific binding, it tries to create an instance. In the example below, it instantiates the `MySQL` class in the provided code. But if it encounters an abstract class or an interface that can't be instantiated directly, an error occurs.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();

// No (explicit) binding here!

$database = $container->get(MySQL::class);
```

### Binding to Objects

[](#binding-to-objects)

You can connect abstracts to specific objects. Using singleton binding gives you the original object when required, while transient binding offers a fresh copy of the object every time you ask for it.

```
use MiladRahimi\PhpContainer\Container;

$user = new User();
$user->name = 'Milad';

$container = new Container();

$container->singleton('user', $user);
// OR
$container->transient('user', $user);
```

### Constructor Auto-injection

[](#constructor-auto-injection)

Concrete classes might contain constructor parameters that either possess default values or can be resolved by the container.

```
use MiladRahimi\PhpContainer\Container;

class Notifier implements NotifierInterface
{
    public MailInterface $mail;
    public Vonage $vonage;
    public string $sender;

    public function __constructor(MailInterface $mail, Vonage $vonage, $sender = 'PhpContainer')
    {
        $this->mail = $mail;
        $this->vonage = $vonage;
        $this->sender = $sender;
    }
}

$container = new Container();
$container->transient(MailInterface::class, MailTrap::class);
$container->transient(NotifierInterface::class, Notifier::class);

$notifier = $container->get(NotifierInterface::class);
print_r($notifier->mail);   // $mail would be an instnace of MailTrap (explicit binding)
print_r($notifier->vonage); // $vonage would be an instnace of Vonage (implicit binding)
print_r($notifier->sender); // $sender would be "PhpContainer" (default value)
```

### Binding Using Closure

[](#binding-using-closure)

The following example illustrates how to bind using Closure.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();

$container->singleton(Config::class, function () {
    return new JsonConfig('/path/to/config.json');
});

// $config would be auto-injected
$container->singleton(Database::class, function (Config $config) {
    return new MySQL(
        $config->get('database.host'),
        $config->get('database.port'),
        $config->get('database.name'),
        $config->get('database.username'),
        $config->get('database.password')
    );
});
```

In singleton binding, the container executes the Closure once and retrieves the result whenever needed. Conversely, in transient binding, the container invokes the Closure each time it's required. If you intend to bind an abstraction to a Closure without immediate invocation by the container, you can use the `closure()` method instead.

### Resolving Using Closure

[](#resolving-using-closure)

You have the option to use the `call` method, allowing the container to execute the provided function or closure and resolve its arguments.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();
$container->singleton(MailInterface::class, MailTrap::class);

// Direct Closure call
$response = $container->call(function(MailerInterface $mailer) {
    return $mailer->send('info@example.com', 'Hello...');
});

// Direct function call
function sendMail(MailerInterface $mailer) {
    return $mailer->send('info@example.com', 'Hello...');
}
$response = $container->call('sendMail');

// Direct method call
class UserManager {
    function sendMail(MailerInterface $mailer) {
        return $mailer->send('info@example.com', 'Hello...');
    }
}
$response = $container->call([UserManager::class, 'sendMail']);
```

### Type-based and name-based binding

[](#type-based-and-name-based-binding)

PhpContainer supports typed-based and name-based bindings. The following example demonstrates these types of bindings.

```
use MiladRahimi\PhpContainer\Container;

$container = new Container();

// Type-based binding
$container->singleton(Database::class, MySQL::class);
$container->call(function(Database $database) {
    $database->ping();
});

// Name-based binding
$container->singleton('$number', 666);
$container->call(function($number) {
    echo $number; // 666
});
```

### Error handling

[](#error-handling)

The `ContainerException` might be raised by the container for several reasons. It can arise when a `ReflectionException` occurs, indicating a missing concrete implementation for a provided abstraction. Additionally, this exception occures when the container cannot inject parameter values into concrete constructors or closures.

License
-------

[](#license)

PhpContainer is created by [Milad Rahimi](https://miladrahimi.com) and released under the [MIT License](http://opensource.org/licenses/mit-license.php).

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity72

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

Recently: every ~258 days

Total

19

Last Release

946d ago

Major Versions

1.0 → 2.02017-06-22

2.0 → v3.02018-09-19

v3.0 → v4.0.02020-08-16

v4.2.2 → v5.0.02020-11-20

PHP version history (7 changes)1.0PHP &gt;=5.3.0

2.0PHP &gt;=5.4.0

v3.0PHP ^7.0

v4.0.0PHP ^7.1

v5.2.4PHP ^7.1|^8.0

v5.3.0PHP ^7.2|^8.0

v5.3.2PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/921274b8bb29236d8f94f6c83100a5f751f6394c4c49741e1b92bfbccac0911b?d=identicon)[miladrahimi](/maintainers/miladrahimi)

---

Top Contributors

[![miladrahimi](https://avatars.githubusercontent.com/u/6689295?v=4)](https://github.com/miladrahimi "miladrahimi (37 commits)")

---

Tags

containerdependency-injectioniocphppsr-11psr-11-compliantcontainerdependencyinjectiondiiocdiccontrolinversion

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/miladrahimi-phpcontainer/health.svg)

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

###  Alternatives

[league/container

A fast and intuitive dependency injection container.

86894.4M442](/packages/league-container)[capsule/di

A PSR-11 compliant autowiring dependency injection container.

2860.1k2](/packages/capsule-di)[slince/di

A flexible dependency injection container

20272.1k6](/packages/slince-di)

PHPackages © 2026

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