PHPackages                             pchouse/php-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. pchouse/php-di

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

pchouse/php-di
==============

A dependency injection library

1.0.0(2y ago)04MITPHPPHP ~8.2 || ~8.3

Since Dec 20Pushed 2y ago1 watchersCompare

[ Source](https://github.com/pchouse/php-di)[ Packagist](https://packagist.org/packages/pchouse/php-di)[ Docs](https://github.com/pchouse/php-di)[ RSS](/packages/pchouse-php-di/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (7)Versions (2)Used By (0)

PChouse PHP-DI
==============

[](#pchouse-php-di)

---

##### Dependency injection library

[](#dependency-injection-library)

#### Install

[](#install)

```
composer require pchouse/php-di
```

#### Usage

[](#usage)

Crete a binds file that return an array
Binds.php

```
    return [

        new Bind(
            Scope::TRANSIENT,
            IDependency::class,
            Dependency::class
        ),

        new Bind(
            Scope::TRANSIENT,
            IDependencyWiredOne::class,
            DependencyWiredOne::class
        ),

        new Bind(
            Scope::TRANSIENT,
            IDependencyWiredTwo::class,
            DependencyWiredTwo::class
        ),

        new Bind(
            Scope::SINGLETON,
            IDependencyWiredSingleton::class,
            DependencyWiredSingleton::class
        ),

        new Bind(
            Scope::PROVIDES,
            DependencyProvides::class,
            function () {
                $provides = new DependencyProvides();
                $provides->setRandom(
                    (new Randomizer())->getInt(9, 99999)
                );
                return $provides;
            }
        ),

        new Bind(
            Scope::SINGLETON,
            DependencyProvidesSingleton::class,
            function () {
                $provides = new DependencyProvidesSingleton();
                $provides->setRandom(
                    (new Randomizer())->getInt(9, 99999)
                );
                return $provides;
            }
        ),
    ];
```

Create a Routes file that return an array
Routes.php

```
    return [
        new Bind(Scope::ROUTE, IDependencyController::class, DependencyController::class),
    ];
```

In your bootstrap.php or other place configure the container

```

    Container::$bindsFilePath  = "/path/to/Binds.php";
    Container::$routesFilePath = "/path/to/Routes.php";
```

Example of a class using Injection
Mark the constructor with #\[Inject\] if it has arguments
Mark the properties to be injected with #\[Inject\] If you desire to use Events implement the IDIEvents interface

```

    class Dependency implements IDIEvents, IDependency
    {

        private bool $afterInstanceCreatedInit = false;

        private bool $beforeReturnInstanceInit = false;

        #[Inject]
        private IDependencyWiredOne $dependencyWiredOne;

        private int $rand = 0;

        #[Inject]
        public function __construct(private IDependencyWiredTwo $dependencyWiredTwo)
        {
        }

        public function getDependencyWiredOne(): IDependencyWiredOne
        {
            return $this->dependencyWiredOne;
        }

        public function setDependencyWiredOne(IDependencyWiredOne $dependencyWiredOne): void
        {
            $this->dependencyWiredOne = $dependencyWiredOne;
        }

        public function getDependencyWiredTwo(): IDependencyWiredTwo
        {
            return $this->dependencyWiredTwo;
        }

        public function setDependencyWiredTwo(IDependencyWiredTwo $dependencyWiredTwo): void
        {
            $this->dependencyWiredTwo = $dependencyWiredTwo;
        }

        public function afterInstanceCreated(): void
        {
            $this->afterInstanceCreatedInit = true;
        }

        /**
         * @throws \Exception
         */
        public function beforeReturnInstance(): void
        {
            if (!$this->afterInstanceCreatedInit) {
                throw new \Exception(
                    "The AfterInstanceCreated did not run"
                );
            }
            $this->beforeReturnInstanceInit = true;
        }

        public function isAfterInstanceCreatedInit(): bool
        {
            return $this->afterInstanceCreatedInit;
        }

        public function isBeforeReturnInstanceInit(): bool
        {
            return $this->beforeReturnInstanceInit;
        }

        public function getRand(): int
        {
            return $this->rand;
        }

        public function setRand(int $rand):void
        {
            $this->rand = $rand;
        }
    }
```

If in any part of the code to get manually an instance

```

    $instance = \PChouse\Di\Container::get(ICalssName);
    // OR
    $route = \PChouse\Di\Container::getRoute(IClassName);
```

In test mode to build with mocks
In the test bootstrap.php set a constant: const PHP\_DI\_TEST = 1;
Only the instance marked with mock will be replaced in the container

```

     Container::build(
            [
                new Bind(Scope::MOCK, IDependencyWiredSingleton::class, $mock)
            ]
     );

     $dependency = Container::get(IDependency::class);
```

Scopes

```

    Scope::TRANSIENT // Allways a new instance
    Scope::SINGLETON // Create a singleton instance
    Scope::PROVIDES  // For manually created instaces
```

License

Copyright 2023 Reflexão, Sistemas e Estudos Informáticos, Lda

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

[](#the-software-is-provided-as-is-without-warranty-of-any-kind-express-or-impliedincluding-but-not-limited-to-the-warranties-of-merchantability-fitness-for-a-particular-purpose-and-noninfringementin-no-event-shall-the-authors-or-copyright-holders-be-liable-for-any-claim-damages-or-other-liabilitywhether-in-an-action-of-contract-tort-or-otherwise-arising-from-out-of-or-in-connection-with-the-software-orthe-use-or-other-dealings-in-the-software)

##### Art made by a Joseon Chinnampo soul for smart people 🇰🇷

[](#art-made-by-a-joseon-chinnampo-soul-for-smart-people-)

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

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

870d ago

### Community

Maintainers

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

---

Tags

phpdiservice containerDendency injection

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[hyperf/di

A DI for Hyperf.

182.8M594](/packages/hyperf-di)[imanghafoori/laravel-anypass

A minimal yet powerful package to help you in development.

21421.6k](/packages/imanghafoori-laravel-anypass)

PHPackages © 2026

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