PHPackages                             sasa-b/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. sasa-b/container

ActiveLibrary[Framework](/categories/framework)

sasa-b/container
================

Lightweight dependency injection container with laravel like autowiring, interface/abstract class binding and contextual binding. PSR-11 compliant.

1.0.1(8y ago)1271MITPHP

Since Oct 7Pushed 8y ago1 watchersCompare

[ Source](https://github.com/sasa-b/container)[ Packagist](https://packagist.org/packages/sasa-b/container)[ RSS](/packages/sasa-b-container/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (2)Dependencies (1)Versions (4)Used By (0)

IOC container
=============

[](#ioc-container)

Lightweight dependency injection container with laravel like autowiring, interface/abstract class binding and contextual binding. PSR-11 compliant.

---

To use the library clone the repo or just use composer to install it.

`composer require sasa-b/container`

Usage examples
--------------

[](#usage-examples)

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

$container = new Foundation\Container\Container();`
```

#### Binding/Registering services

[](#bindingregistering-services)

A service (bound value) can be a string representation of a class, an anonymous function which returns an object instance, or an object instance itself. If you bind an object instance itself, that service will essentially act as a singleton because the same instance will always be returned.

```
$container->bind(Foo\Bar::class, Foo\Bar::class);

$container->bind(Foo\Bar::class, function ($container) {
   return new \Foo\Bar($container['Foo\Baz']);

});

$container->bind('Foo\Bar', FooBar::class);

$container->bind(Foo\Bar::class, new \Foo\Bar());
```

##### Singletons

[](#singletons)

```
   $container->bind('Foo\Bar', FooBar::class)->share();

   //or

   $container->bind('Foo\Bar', FooBar::class);
   $container->share(Foo\Bar::class);

   $container->bind(Foo\Baz::class, Foo\Baz::class)->mapTo('baz');
   $container->share('baz');
```

#### Mapping services to keys

[](#mapping-services-to-keys)

For convenience you can map your services to keys and there are multiple ways of doing it.

1. With mapTo method via method chaining

```
$container->bind(Foo\Bar::class, Foo\Bar::class)->mapTo('foo');
```

2. With the key method

```
$container->key('foo', Foo\Bar::class);
```

3. Directly with the bind statement

```
$container->bind('foo', function ($container) {
   return new Foo\Bar();
});
```

When you directly bind services to a *key*, they will only be accessible by that *key* and those services can't be used for **autowiring (injecting by type hinting)**, unless the service you are binding/registering is a string representaton of a class, in that case the service will automatically be mapped to the given *key*.

In case of `mapTo` and `key` bound/registered services are accessible by both the key and their class name, and because of that they can be used for autowiring.

#### Binding/Registering multiple services

[](#bindingregistering-multiple-services)

For registering multiple services at once you can use the `register` method or it's alias `bindMany`.

```
$container->register([
    Foundation\Request\Http::class => Foundation\Request\Http::class,
    Foundation\Sessions\SessionManager::class => \Foundation\Sessions\SessionManager::class,
    Foundation\Request\Cookie::class => Foundation\Request\Cookie::class,
    'date' => \DateTime::class,
    Foundation\Core\Database::class => Foundation\Core\Database::class,
    Foundation\Database\QueryBuilder::class => (function ($c) {
        return new \Foundation\Database\PDOQuery($c['db']);
    })
])->mapTo(['request', 'session', 'cookie', 'db']);

$container->register([
    Foundation\Request\Http::class => Foundation\Request\Http::class,
    Foundation\Sessions\SessionManager::class => \Foundation\Sessions\SessionManager::class,
    Foundation\Request\Cookie::class => Foundation\Request\Cookie::class
]);

$container->keys([
   'request' => Foundation\Request\Http::class,
   'session' => Foundation\Sessions\SessionManager::class,
   'cookie' => Foundation\Request\Cookie::class
]);
```

##### Registering multiple singletons

[](#registering-multiple-singletons)

```
/* Only those specified will be registered as singletons */
$container->register([
    Foundation\Request\Http::class => Foundation\Request\Http::class,
    Foundation\Sessions\SessionManager::class => \Foundation\Sessions\SessionManager::class,
    Foundation\Request\Cookie::class => Foundation\Request\Cookie::class,
    'date' => \DateTime::class,
    Foundation\Core\Database::class => Foundation\Core\Database::class,
    Foundation\Database\QueryBuilder::class => (function ($c) {
        return new \Foundation\Database\PDOQuery($c['db']);
    })
])->share(['session', 'db', Foundation\Core\Database::class]);

/* All will be registered as singletons */
$container->register([
    Foundation\Request\Http::class => Foundation\Request\Http::class,
    Foundation\Sessions\SessionManager::class => \Foundation\Sessions\SessionManager::class,
    Foundation\Request\Cookie::class => Foundation\Request\Cookie::class,
    'date' => \DateTime::class,
    Foundation\Core\Database::class => Foundation\Core\Database::class,
    Foundation\Database\QueryBuilder::class => (function ($c) {
        return new \Foundation\Database\PDOQuery($c['db']);
    })
])->share();
// or
$container->register([
    Foundation\Request\Http::class => Foundation\Request\Http::class,
    Foundation\Sessions\SessionManager::class => \Foundation\Sessions\SessionManager::class,
    Foundation\Request\Cookie::class => Foundation\Request\Cookie::class,
    'date' => \DateTime::class,
    Foundation\Core\Database::class => Foundation\Core\Database::class,
    Foundation\Database\QueryBuilder::class => (function ($c) {
        return new \Foundation\Database\PDOQuery($c['db']);
    })
], true);
```

#### Abstract binding

[](#abstract-binding)

You can bind/register services to interfaces and abstract classes as well. These abstract bindings are convenient when used with autowiring, because you can type hint with abstractions (abstract classes and interfaces) and not concretions (implementations).

```
$container->bind(Foo\BarInterface::class, Foo\Bar::class);
$container->bind(Foo\AbstractBaz::class, Foo\Baz::class);
```

##### Contextual binding

[](#contextual-binding)

When you want to bind/register multiple different services to a same interface or abstract class you need to provide *context* otherwise one will override the other. *Context* is the third parameter to the `bind` method, and it can be a string representation of a class or a key mapped to a class, and that class needs to be the one in whose constructor or method the interface/abstract class is used as a typehint.

```
// This will result in an override and `Foo\Baz::class` will always be returned for Foo\Bar::interface
$container->bind(Foo\BarInterface::class, Foo\Bar::class);
$container->bind(Foo\BarInterface::class, Foo\Baz::class);

$container->bind(Foo\BarInterface::class, Foo\Bar::class);
$container->bind(Foo\BarInterface::class, Foo\Baz::class, 'FooController');
```

#### Retrieveing services

[](#retrieveing-services)

```
$service = $container['Foo\Bar'];
$service = $container[Foo\Bar::class];
$service = $container['foo'];

// Only works for services mapped to keys
$service = $container->foo();
$service = $container->foo;

// Retrieves a new instance or a singleton if a service has been registered as a singleton
$service = $container->get('foo');

// Always retrieves a singleton
$service = $container->shared('foo');
```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity65

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

Total

3

Last Release

3140d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b69f1d9205d4b96ec1c90ff7bc2503f1d14ea4b0b89b82b406c16f922c634133?d=identicon)[sasa-b](/maintainers/sasa-b)

---

Top Contributors

[![sasa-b](https://avatars.githubusercontent.com/u/18427949?v=4)](https://github.com/sasa-b "sasa-b (27 commits)")

---

Tags

containerdependencydependency-injectiondependency-injection-containeriocioc-containerlibraryphp

### Embed Badge

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

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[silverstripe/framework

The SilverStripe framework

7213.5M2.5k](/packages/silverstripe-framework)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6939.5M343](/packages/drupal-core-recommended)[cakephp/core

CakePHP Framework Core classes

6026.8M39](/packages/cakephp-core)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)

PHPackages © 2026

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