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

AbandonedArchivedLibrary[Framework](/categories/framework)

njasm/container
===============

Dependency Container for PHP

1.2.11(10y ago)2059.9k—1.5%3[3 issues](https://github.com/njasm/container/issues)[1 PRs](https://github.com/njasm/container/pulls)1MITPHPPHP &gt;=5.3

Since Jun 9Pushed 7y ago1 watchersCompare

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

READMEChangelogDependencies (13)Versions (22)Used By (1)

[![Build Status](https://camo.githubusercontent.com/d5a7d20d51c418202680b10bf666929230e242dbfbab9917b87ea1c81e41f058/68747470733a2f2f7472617669732d63692e6f72672f6e6a61736d2f636f6e7461696e65722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/njasm/container) [![Code Coverage](https://camo.githubusercontent.com/7469977054865673587f85c80a72fedc54dfb11f067ac78a42f63c6cfc89d3f7/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e6a61736d2f636f6e7461696e65722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/njasm/container/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/6861864905b3885a0c6f964cb95efe83f54f7089c69cb2a918b99555ff213ca9/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e6a61736d2f636f6e7461696e65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/njasm/container/?branch=master)[![Total Downloads](https://camo.githubusercontent.com/e69e39e8085777f0d735406ba09b49b51a6e01ecaa8b5d937e5662fd4332ef5e/68747470733a2f2f706f7365722e707567782e6f72672f6e6a61736d2f636f6e7461696e65722f646f776e6c6f6164732e706e67)](https://packagist.org/packages/njasm/container)[![Latest Stable Version](https://camo.githubusercontent.com/0668e2f97b7310c68a7ad52d1e0e18ad0aefc23b52fe7efb9d255a742ca185b4/68747470733a2f2f706f7365722e707567782e6f72672f6e6a61736d2f636f6e7461696e65722f762f737461626c652e706e67)](https://packagist.org/packages/njasm/container) [![License](https://camo.githubusercontent.com/6d11335d0292249a523f824c3048f64d8416c1fbf661668ae650888aac1eba40/68747470733a2f2f706f7365722e707567782e6f72672f6e6a61736d2f636f6e7461696e65722f6c6963656e73652e706e67)](https://packagist.org/packages/njasm/container)[![HHVM Status](https://camo.githubusercontent.com/13bf8e526fb508b38222fba37025787fa5b1ae74b6564cf28839b827d150c9e1/687474703a2f2f6868766d2e683463632e64652f62616467652f6e6a61736d2f636f6e7461696e65722e706e67)](http://hhvm.h4cc.de/package/njasm/container)

Dependency Container / Service Locator
--------------------------------------

[](#dependency-container--service-locator)

### Features

[](#features)

- Alias Service Keys support
- Circular Dependency guard
- Primitive data-types registration
- Automatic Constructor Dependency Resolution and Injection for non-registered Services
- Lazy and Eager instantiation approaches
- Lazy and Eager Instantiation Singleton services registration
- Support for public Setter injection/Method calls after service instantiation
- Support for public Properties/Attributes Injection after Service instantiation
- Ability to override existing dependency (Properties &amp; Setters) declarations by supplying new ones when call to `Container::get`
- Nested Providers/Containers support
    - [Aura.DI ](https://github.com/auraphp/Aura.Di)
    - [Joomla DI](https://github.com/joomla-framework/di)
    - [Laravel](https://github.com/illuminate/container)
    - [Nette DI](https://github.com/nette/di)
    - [Orno DI](https://github.com/orno/di)
    - [Pimple](https://github.com/fabpot/pimple)
    - [PHP-DI](https://github.com/mnapoli/PHP-DI)
    - [Ray.DI](https://github.com/koriym/Ray.Di)
    - [Symfony](https://github.com/symfony/DependencyInjection)
    - [zf2 DI](https://github.com/zendframework/Component_ZendDi)
    - more to come...
- Comply with `Container-Interop` interfaces

### Requirements

[](#requirements)

- PHP 5.3 or higher.

### Installation

[](#installation)

Include `njasm\container` in your project, by adding it to your `composer.json` file.

```
{
    "require": {
        "njasm/container": "~1.0"
    }
}
```

Usage
-----

[](#usage)

To create a container, simply instantiate the `Container` class.

```
use Njasm\Container\Container;

$container = new Container();
```

### Using Alias

[](#using-alias)

There are time that your `key` are too long to be convenient for your client code, one example for instance, is when binding an `interface` to an `implementation` or when using for your `key` the FQCN of your classes.

```
namespace Very\Long\Name\Space;

interface SomeInterface {}

class SomeImplementation implements SomeInterface
{
    // code here
}

$container = new Njasm\Container\Container();
$container->set('Very\Long\Name\Space\SomeInterface', new SomeImplementation());
$container->alias('Some', 'Very\Long\Name\Space\SomeInterface');

$some = $container->get('Some');
```

### Defining Services

[](#defining-services)

Services are defined with two params. A `key` and a `value`. The order you define your services is irrelevant.

#### Defining Services - Primitive data-types

[](#defining-services---primitive-data-types)

```
$container->set("Username", "John");

echo $container->get("Username");
```

#### Defining Services - Binding Services (Lazy Loading)

[](#defining-services---binding-services-lazy-loading)

You can bind a `key` to a instantiable FCQN `value`.

```
$container->bind("MyKey", "\My\Namespace\SomeClass");
```

If you want to bind a Service, and register that Service as a `Singleton` Service.

```
$container->bindSingleton("MyKey", "\My\Namespace\SomeClass");
```

Both `Container::bind` and `Container::bindSingleton` uses Lazy Loading approach, so that `\My\Namespace\SomeClass` will only be evaluated/instantiated when `MyKey` is requested.

When binding a service, constructor dependencies can be declared, public attributes be set and methods called with arguments, so they are injected/setted when instantiating the service.

```
namespace \App\Actors;

class Person {
    protected $name;
    protected $age = 24;
    public genre = 'Male';

    public function __construct($name = 'John') {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function getAge() {
        return $this->age;
    }

    public function setAge($age) {
        $this->age = (int) $age;
    }
}

$container->bind(
    "Person",                       // key
    "\App\Actors\Person",           // FQCN
    array("Jane"),                  // constructor dependencies
    array("genre" => "Female"),     // attributes injection
    array("setAge" => array(33))    // call methods
);

// binding with chaining methods
$container->bind("Person", '\App\Actors\Person')
    ->setConstructorArguments(array("Jane"))        // setConstructorArgument($index, $argument)
    ->setProperty("genre" => "Female")              // setProperties(array("genre" => "Female", ...) also work
    ->callMethod("setAge", array(33));              // callMethods(array('methodName' => 'methodValue', ...));

// retrieving the object
$person = $container->get("Person");
echo $person->getName(); // Jane
echo $person->getAge();  // 33
echo $person->genre      // Female

// calling services and overriding declared dependencies
$person2 = $container->get(
    "Person",
    array("Mark"),
    array("genre" => "Male"),
    array("setAge" => array(55))
);
echo $person2->getName(); // Mark
echo $person2->getAge();  // 55
echo $person2->genre      // Male
```

#### Defining Services - Objects (Eager Loading)

[](#defining-services---objects-eager-loading)

```
$mailer = new \Namespace\For\My\MailTransport(
    "smtp.example.com",
    "username",
    "password",
    25
);

$container->set(
    "Mail.Transport",
    $mailer,
    array(), // constructor args
    array(), // public properties injection
    array("withSSL" => array(false)) // calling methods
);

$mailerTransport = $container->get("Mail.Transport");
```

Overwriting existent declared dependencies is also possible for `set` definitions.

```
// calling methods and injecting attributes is also possible
$mailerTransportSsl = $container->get(
    "Mail.Transport",
    array(),
    array(),
    array("withSSL" => array(true))
);
```

#### Defining Services - Complex builds (Lazy Loading)

[](#defining-services---complex-builds-lazy-loading)

There are time when you'll want to instantiate an object, but the build process is reall complex and you want to control that process. You use anonymous functions for that.

```
$container->set(
    "Complex",
    function($firstName = "John", $lastName = "Doe") {
        // complex logic here
        // ...
        $theComplexObject = new Complex($firstName, $lastName);

        return $theComplexObject;
    }
);

$complex = $container->get("Complex");

// injecting closure dependencies is also possible
$complexJane = $container->get("Complex", array("Jane", "Fonda"));
```

#### Defining Services - Complex builds With Nested Dependencies (Lazy Loading)

[](#defining-services---complex-builds-with-nested-dependencies-lazy-loading)

Creation of nested dependencies is also possible. You just need to pass the container to the closure.

```
$container->set(
    "Mail.Transport",
    function() use (&$container) {
        return new \Namespace\For\My\MailTransport(
            $container->get("Mail.Transport.Config")
        );
    }
);

$container->set(
    "Mail.Transport.Config",
    function() {
        return new \Namespace\For\My\MailTransportConfig(
            "smtp.example.com",
            "username",
            "password",
            25
        );
    }
);

$mailer = $container->get("Mail.Transport");
```

#### Defining Singleton Services

[](#defining-singleton-services)

For registering singleton services, you use the singleton method invocation.

```
$container->singleton(
    "Database.Connection",
    function() {
        return new \Namespace\For\My\Database(
            "mysql:host=example.com;port=3306;dbname=your_db",
            "username",
            "password"
        );
    }
);

// MyDatabase is instantiated and stored, for future requests to this service,
// and then returned.
$db = $container->get("Database.Connection");
$db2 = $container->get("Database.Connection");

// $db === $db2 TRUE
```

### Defining Sub/Nested Containers

[](#defining-subnested-containers)

Nesting container is possible as long as you use an existing Container Adapter for your application existing container. The Adapter class must implement the `ServicesProviderInterface` for more examples please see the `Adapter`folder.

```
$pimple; // is your instantiated pimple container
$pimple["Name"] = $pimple->factory(function() {
   return "John";
}

$pimpleAdapter = new \Njasm\Container\Adapter\PimpleAdapter($pimple);
$mainContainer = new \Njasm\Container\Container();
$mainContainer->provider($pimpleAdapter);

$mainContainer->has("Name"); // TRUE
echo $mainContainer->get("Name"); // John
```

### Automatic Resolution of Services

[](#automatic-resolution-of-services)

When the Container is requested for a service that is not registered, it will try to find the class, and will automatically try to resolve your class's constructor dependencies.

```
namespace My\Name\Space;

class Something
{
    // code
}

// without registering the Something class in the container you can...
$container = new Njasm\Container\Container();
$something = $container->get('My\Name\Space\Something');

//$something instanceof 'My\Name\Space\Something' == true

//once again you can also inject dependencies when calling get method.
$something = $container->get(
    "My\Name\Space\Something",
    array("constructor value 1", "constructor value 2"),
    array("attributeName" => "value 1"), // attributes
    array("methodName" => array("value 1", "value 2"))
);
```

### Roadmap

[](#roadmap)

In no Particular order - check Milestones for a more organized picture.

- Load definitions from configuration files
- Optimizations

### Contributing

[](#contributing)

Do you wanna help on feature development/improving existing code through refactoring, etc? Or wanna discuss a feature/bug/idea? Issues and Pull Requests are welcome as long as you follow some guidelines for PRs:

Pull Requests must:

- Be PSR-2 compliant.
- Submit tests with your pull request to your own changes / new code introduction.
- having fun.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance17

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity67

Established project with proven stability

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

Recently: every ~287 days

Total

17

Last Release

3065d ago

Major Versions

1.2.11 → 2.0.x-dev2017-12-26

PHP version history (3 changes)1.0.0PHP &gt;=5.4

1.0.1PHP &gt;=5.3

2.0.x-devPHP &gt;=7.0

### Community

Maintainers

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

---

Tags

containerdependency-injectionphpphp-librarydependency-injectioniocdicDependency-Container

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[rdlowrey/auryn

Auryn is a dependency injector for bootstrapping object-oriented PHP applications.

7262.2M76](/packages/rdlowrey-auryn)[nette/di

💎 Nette Dependency Injection Container: Flexible, compiled and full-featured DIC with perfectly usable autowiring and support for all new PHP features.

92340.6M1.4k](/packages/nette-di)[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)[joomla/di

Joomla DI Package

15391.2k11](/packages/joomla-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)[mouf/picotainer

This package contains a really minimalist dependency injection container compatible with container-interop.

16189.8k11](/packages/mouf-picotainer)

PHPackages © 2026

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