PHPackages                             pierredup/di - 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. [Framework](/categories/framework)
4. /
5. pierredup/di

ActiveLibrary[Framework](/categories/framework)

pierredup/di
============

A dynamic dependency injection manager

v0.1.0(12y ago)019[4 issues](https://github.com/pierredup/Di/issues)MITPHP

Since Jan 8Pushed 12y ago1 watchersCompare

[ Source](https://github.com/pierredup/Di)[ Packagist](https://packagist.org/packages/pierredup/di)[ RSS](/packages/pierredup-di/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (1)DependenciesVersions (2)Used By (0)

Dynamic Dependency Injection
============================

[](#dynamic-dependency-injection)

[![Build Status](https://camo.githubusercontent.com/0d96afd35a396116a70c03e0178d8828743b9cca7cf4d810e96e6c5f57f7e315/68747470733a2f2f7472617669732d63692e6f72672f7069657272656475702f44692e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/pierredup/Di)[![Scrutinizer Quality Score](https://camo.githubusercontent.com/f3ca0d3ac00b5802862dc761b5fe8782a28c163609ff70832445b2ae9f571a15/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7069657272656475702f44692f6261646765732f7175616c6974792d73636f72652e706e673f733d63643164363332306230353939303266316134373338373037666537356235616239326263653939)](https://scrutinizer-ci.com/g/pierredup/Di/)[![Code Coverage](https://camo.githubusercontent.com/0526364fee19174c5f15e5a66cbf65d9ad6030e67eef12d1aebf635521736f27/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7069657272656475702f44692f6261646765732f636f7665726167652e706e673f733d37336261366533653063306662656564393364666538353734333533383162366562356438353839)](https://scrutinizer-ci.com/g/pierredup/Di/)

This library provides a class to handle dependency injection dynamically.

Dynamic dependency injection means you don't have to define services or define which dependencies needs to be injected. The dependencies is dynamically created based on the constructor parameters.

This means you only need to add type-hints for the classes you want to inject into your class constructor.

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

[](#installation)

### Composer

[](#composer)

To install this library using [composer](http://getcomposer.org/), add the following to your `composer.json`:

```
{
    "require": {
        "pierredup/di": "*"
    }
}
```

Make sure you are using composer's autoloader to include the file:

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

### Download the file

[](#download-the-file)

Download [Di.phar](https://github.com/pierredup/Di/blob/master/Di.phar) from the repo and save the file into your project path somewhere.

```
require 'path/to/Di.phar';
```

Usage
-----

[](#usage)

### Getting a class with dependencies

[](#getting-a-class-with-dependencies)

```
namespace Foo {

    class Bar
    {
        public function __construct(Baz $baz)
        {
            // ...
        }
    }

    class Baz {

    }
}

$object = Di::get('Foo\Bar');

var_dump($object);
```

This will give you an instance of `Foo\Bar` with the `Baz` class dynamically created and injection into the constructor.

### Getting a new instance of a class

[](#getting-a-new-instance-of-a-class)

By default, the same instance for each class will be returned every time you call `Di::get`If you want to return a new instance of a class, you need to pass a second parameter to the `get` method

```
    $object = Di::get('Foo\Bar', Di::NEW_INSTANCE);
```

This will return a new instance of the `Foo\Bar` class, but the dependencies will always return the same instance.

If you want to ensure that every object returns a new instance, you need to pass the `Di::DEEP` flag:

```
    $object = Di::get('Foo\Bar', Di::DEEP);
```

This will return a new instance of `Foo\Bar`, as well as new instances for each dependency.

### Parameters

[](#parameters)

#### Setting parameters

[](#setting-parameters)

If you have values in your constructor that can not be type-hinted by an object ( E.G database settings), you use can use the `map` method to set the values for those parameters:

```
class Db
{
    public function __construct($host, $username, $password)
    {
        // ...
    }
}

Di::map(array(
    'host'      => 'localhost',
    'username'  => 'user',
    'host'      => 'password',
));

$object = Di::get('Db');
```

**Note:** If you don't specify a value for a parameter that doesn't have a type-hint, `NULL` will be passed as the value. If you set a default value for the parameter, then the default value will be used instead.

##### Lazy loading parameters

[](#lazy-loading-parameters)

If you want parameters to be lazy-loaded (only load when needed, E.G get value from a database or a session ), you can use a closure or valid callback as the parameter:

```
Di::map(array(
    'parameter' => function() {
        return Di::get('Foo\Database')->getValueFromDb()
    }
));

// OR

Di::map(array(
    'parameter' => array($db, 'getValueFromDb')
));
```

The function or callback will only be executed when the parameter is needed, and the value will then be cached for any further calls.

#### Getting parameters

[](#getting-parameters)

To get a parameter value, just pass the `Di::PARAM` flag to the get method:

```
Di::map(array(
    'host'      => 'localhost',
    'username'  => 'user',
    'host'      => 'password',
));

$host = Di::get('host', Di::PARAM); // return 'localhost'
```

#### Over writing classes

[](#over-writing-classes)

You can also use the `map` method to over write a class name. This is useful if you want to over write a core class of a library with your own implementation. Note that your class needs to extend from the class you are over writing, otherwise you might get an error or unexpected results.

```
namespace Foo {
    class Bar
    {

    }
}

namespace Baz {
    use Foo\Bar;

    class FooBar extends Bar
    {

    }
}

Di::map(array(
    'Foo\Bar' => 'Baz\FooBar'
));

$object = Di::get('Foo\Bar'); // will return an instance of `Baz\FooBar`
```

TODO
----

[](#todo)

- Setter Injection [\#1](https://github.com/pierredup/Di/issues/1)
- Cache class instances [\#2](https://github.com/pierredup/Di/issues/2)
- Define services [\#3](https://github.com/pierredup/Di/issues/3)
- Map interface to concrete class [\#4](https://github.com/pierredup/Di/issues/4)

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

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

Unknown

Total

1

Last Release

4511d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b374a94bdeca7fd62b1debf578810b58c63b6bb73bb648c4d3b3876aefe05a1d?d=identicon)[pierredup](/maintainers/pierredup)

---

Top Contributors

[![pierredup](https://avatars.githubusercontent.com/u/144858?v=4)](https://github.com/pierredup "pierredup (10 commits)")

---

Tags

dependencyinjectiondependency-injectiondi

### Embed Badge

![Health badge](/badges/pierredup-di/health.svg)

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

###  Alternatives

[yiisoft/di

Yii DI container

2351.2M100](/packages/yiisoft-di)[yiisoft/injector

PSR-11 compatible injector. Executes a callable and makes an instances by injecting dependencies from a given DI container.

942.8M38](/packages/yiisoft-injector)[mouf/mouf

The Mouf PHP framework: an open-source PHP framework providing an easy way to download, install, use and reuse components, with a graphical user interface.

55146.0k17](/packages/mouf-mouf)[capsule/di

A PSR-11 compliant autowiring dependency injection container.

2857.5k2](/packages/capsule-di)[mouf/pimple-interop

This project is a very simple extension to the Pimple microframework. It adds to Pimple compatibility with the container-interop APIs.

102.4M2](/packages/mouf-pimple-interop)[joomla/di

Joomla DI Package

15391.2k11](/packages/joomla-di)

PHPackages © 2026

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