PHPackages                             mmghv/dependency-pocket - 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. mmghv/dependency-pocket

AbandonedArchivedLibrary

mmghv/dependency-pocket
=======================

A new form of Dependency Injection in PHP

v0.2.1(9y ago)118MITPHPPHP &gt;=5.4.0

Since Sep 30Pushed 8y ago1 watchersCompare

[ Source](https://github.com/mmghv/dependency-pocket)[ Packagist](https://packagist.org/packages/mmghv/dependency-pocket)[ Docs](https://github.com/mmghv/dependency-pocket)[ RSS](/packages/mmghv-dependency-pocket/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

DependencyPocket
================

[](#dependencypocket)

[![Build Status](https://camo.githubusercontent.com/e95da217bc190c651f4b83d2947c25997fb956c5ba2958f2c667e8f563a0c06b/68747470733a2f2f7472617669732d63692e6f72672f6d6d6768762f646570656e64656e63792d706f636b65742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/mmghv/dependency-pocket)[![Latest Stable Version](https://camo.githubusercontent.com/134f1571dbfb401ea2ff3d52820d2fce06dc93419dd5918d0b65933f51b4707b/68747470733a2f2f706f7365722e707567782e6f72672f6d6d6768762f646570656e64656e63792d706f636b65742f762f737461626c65)](https://packagist.org/packages/mmghv/dependency-pocket)[![Latest Unstable Version](https://camo.githubusercontent.com/25a30115b01573c1afd7b9c2d92fa7919d056e6aabb1e65f153c352ea053eac6/68747470733a2f2f706f7365722e707567782e6f72672f6d6d6768762f646570656e64656e63792d706f636b65742f762f756e737461626c65)](https://packagist.org/packages/mmghv/dependency-pocket)[![License](https://camo.githubusercontent.com/876146a2b3633b828c588f1fc04e8180eb2fdd09ded0e99fffaf89f8e13fb192/68747470733a2f2f706f7365722e707567782e6f72672f6d6d6768762f646570656e64656e63792d706f636b65742f6c6963656e7365)](https://packagist.org/packages/mmghv/dependency-pocket)

A new form of "Dependency Injection" in PHP

Not to be confused with [Dependency Injection Container](http://martinfowler.com/articles/injection.html) or `Ioc Container` like [Symfony DI Container](http://symfony.com/doc/current/components/dependency_injection.html), [Pimple](http://pimple.sensiolabs.org/) or [Laravel Service Container](https://laravel.com/docs/5.3/container),

**DependencyPocket** is not a `DI Container` in that way, It's rather a new form of `Dependency Injection`. Essentially, there're two ways of dependency injection : `Constructor Injection` and `Setter Injection`, I'd like to think of this technique as the third type, the `Pocket Injection`.

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

[](#installation)

#### Using composer

[](#using-composer)

```
composer require mmghv/dependency-pocket "~0.2"

```

usage
-----

[](#usage)

We use this pocket inside our classes to hold the dependencies, we first create a new pocket :

```
use mmghv\DependencyPocket;

// ...

$this->pocket = new DependencyPocket();
```

Then we add the dependencies, We first define them (defining the `Name` and the `Type` of each dependency) :

```
$this->pocket->define([
    'dep1',  // allow any type
    'dep2' => 'string',  // primitive type
    'dep3' => 'array',  // primitive type
    'dep4' => 'App\Model\Article'  // class or interface
]);
```

Then we set our dependencies (set dependencies values) :

```
$this->pocket->set([
    'dep1' => true,
    'dep2' => 'some value',
    'dep3' => [1, 2],
    'dep4' => $myArticle
]);
```

Then when we want to get a dependency we simply do :

```
$dep = $this->pocket->get('myDep');
// or
$dep = $this->pocket->myDep;
```

Or we can use `Property Overloading` to easily access our dependencies from our class (or subclasses) :

```
public function __get($name)
{
    if ($this->pocket->has($name)) {
        return $this->pocket->get($name);
    } else {
        throw new \Exception("Undefined property: [$name]");
    }
}
```

When it's useful and the technique to use it
--------------------------------------------

[](#when-its-useful-and-the-technique-to-use-it)

Basically Its useful when your class has many dependencies which not all of them are required so you don't want your constructor to have all these dependencies but still need a way to easily change them in the subclasses and tests.

Imagine you have a class with 5 dependencies but only 2 of them are essential and the other 3 can be set to some default values, Then you extend this class and the subclass can resolve one of the two essential dependencies to a default value and needs to replace one of the optional dependencies of the parent class, You need to be able to do that and want your final class to have only one dependency in the constructor but still be able to change any default ones from any future subclasses as well as the ability to mock any of these dependencies in the tests.

Using **DependencyPocket** you can achieve that like the following without using a setter for each dependency and also mocking dependencies for tests is easier than using `Setter Injection` method :

```
// Manager.php

namespace App\Managers;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use mmghv\DependencyPocket;

class Manager
{
    protected $pocket;

    /**
     * Define class dependencies.
     */
    protected function defineDependencies()
    {
        if ($this->pocket) {
            return true;
        }

        $this->pocket = new DependencyPocket();

        $this->pocket->define([
            'app'           => 'Laravel\Lumen\Application',
            'model'         => 'Illuminate\Database\Eloquent\Model',
            'validator'     => 'Illuminate\Contracts\Validation\Factory',
            'request'       => 'Illuminate\Http\Request',
            'redirectUrl'   => 'string',
        ]);
    }

    /**
     * Create new manager.
     *
     * @param  Application $app
     * @param  Model       $model
     * @param  array       $dependencyPocket
     */
    public function __construct(Application $app, Model $model, array $dependencyPocket = [])
    {
        $this->defineDependencies();

        $this->pocket->set($dependencyPocket += [
            'app'           => $app,
            'model'         => $model,
            'validator'     => $app->make('validator'),  // default value
            'request'       => $app->make('request'),  // default value
            'redirectUrl'   => $app->make('session')->previousUrl(),  // default value
        ]);
    }
}
```

```
// ArticleManager.php

namespace App\Managers;

use Illuminate\Contracts\Foundation\Application;
use App\Models\Article;

class ArticleManager extends Manager
{

    /**
     * Define any additional class dependencies, Declare this function
     * only when you need to define new dependencies.
     */
    protected function defineDependencies()
    {
        if (parent::defineDependencies()) {
            return true;
        }

        $this->pocket->define([
            // define any new dependencies for this class
        ]);
    }

    /**
     * Create new article-manager.
     *
     * @param  Application $app
     * @param  array       $dependencyPocket
     */
    public function __construct(Application $app, array $dependencyPocket = [])
    {
        // always call this first
        $this->defineDependencies();

        // default value for $model dependency
        $model = new Article();

        // call parent construct and pass dependencies
        parent::__construct($app, $model, $dependencyPocket += [
            'validator'     => new CustomValidator(), // replace default dependency value
            // add any new dependencies for this calss, needs to be defined first in 'defineDependencies()'
        ]);
    }
}
```

Then when we instantiate the `ArticleManager` class we only need to pass one dependency like this :

```
$manager = new ArticleManager($app);
```

But also we have the ability to easily replace any default dependencies when we want like this :

```
$manager = new ArticleManager($app, [
    'model' => $anotherModel,
    'validator' => $anotherValidator
]);
```

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

[](#contributing)

This is a relatively new technique so any contributions (suggestions, enhancements to the technique used) are welcome. PSR-2 standards are used and tests should cover any changes in case of PRs.

License &amp; Copyright
-----------------------

[](#license--copyright)

Copyright © 2016, [Mohamed Gharib](https://github.com/mmghv). Released under the [MIT license](LICENSE).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

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

3514d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/88c3da30646097faf255c6c893f71ef8d131ff67328ea6999da59c5097f9194a?d=identicon)[mmghv](/maintainers/mmghv)

---

Top Contributors

[![mmghv](https://avatars.githubusercontent.com/u/5418859?v=4)](https://github.com/mmghv "mmghv (15 commits)")

---

Tags

dependency-injectionpocketdependencyinjectionpocket

### Embed Badge

![Health badge](/badges/mmghv-dependency-pocket/health.svg)

```
[![Health](https://phpackages.com/badges/mmghv-dependency-pocket/health.svg)](https://phpackages.com/packages/mmghv-dependency-pocket)
```

###  Alternatives

[league/container

A fast and intuitive dependency injection container.

86387.8M343](/packages/league-container)[php-di/invoker

Generic and extensible callable invoker

26857.8M56](/packages/php-di-invoker)[yiisoft/di

Yii DI container

2351.2M100](/packages/yiisoft-di)[rg/injektor

Dependency Injection container inspired by google-guice

3973.5k2](/packages/rg-injektor)[reinfi/zf-dependency-injection

A Laminas Framework module for loading dependencies via annotation or config entries.

21115.4k1](/packages/reinfi-zf-dependency-injection)[capsule/di

A PSR-11 compliant autowiring dependency injection container.

2857.5k2](/packages/capsule-di)

PHPackages © 2026

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