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

ActiveLibrary[Framework](/categories/framework)

ody/container
=============

dependency injection container for ODY framework

1.0.0(1y ago)039[1 PRs](https://github.com/ody-dev/container/pulls)3MITPHPPHP &gt;=8.3

Since Mar 13Pushed 1y ago1 watchersCompare

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

READMEChangelog (2)Dependencies (4)Versions (5)Used By (3)

container
=========

[](#container)

⚠️ **IMPORTANT**: This repository is automatically generated from the [ody repo](https://github.com/ody-dev/ody) and is read-only.

Please submit any pull requests or issues to the main ody repo instead.

Container
=========

[](#container-1)

Overview
--------

[](#overview)

The ODY Container is a service container that manages class dependencies and performs dependency injection. Using a container makes it easy to manage and centralize the way objects are created in your application.

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

[](#installation)

```
composer require ody/container
```

Basic Usage
-----------

[](#basic-usage)

### Creating a Container

[](#creating-a-container)

```
use Ody\Container\Container;

$container = new Container();
```

### Binding

[](#binding)

#### Basic Binding

[](#basic-binding)

```
// Bind an interface to a concrete implementation
$container->bind('App\Contracts\UserRepository', 'App\Repositories\DatabaseUserRepository');

// Bind with a closure
$container->bind('database', function ($container) {
    return new PDO('mysql:host=localhost;dbname=myapp', 'username', 'password');
});
```

#### Singleton Binding

[](#singleton-binding)

Singleton bindings only resolve the object once and return the same instance on subsequent calls:

```
$container->singleton('App\Services\PaymentGateway', function ($container) {
    return new App\Services\StripePaymentGateway($container->make('config'));
});
```

#### Instance Binding

[](#instance-binding)

You can bind an existing instance into the container:

```
$config = new Config(['api_key' => 'your-api-key']);
$container->instance('config', $config);
```

### Resolving

[](#resolving)

```
// Resolve from the container
$userRepository = $container->make('App\Contracts\UserRepository');

// Using array access notation
$database = $container['database'];
```

### Auto-Resolution

[](#auto-resolution)

The container can automatically resolve classes with their dependencies:

```
class UserController
{
    protected $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }
}

// The container will automatically resolve the UserRepository dependency
$controller = $container->make(UserController::class);
```

Advanced Features
-----------------

[](#advanced-features)

### Contextual Binding

[](#contextual-binding)

Contextual binding allows you to specify different implementations based on the class that is requesting the dependency:

```
$container->when(PhotoController::class)
          ->needs(Filesystem::class)
          ->give(LocalFilesystem::class);

$container->when(VideoController::class)
          ->needs(Filesystem::class)
          ->give(CloudFilesystem::class);
```

### Tagged Services

[](#tagged-services)

You can tag related bindings and then resolve them all at once:

```
$container->bind('SpeedReport', function () {
    return new SpeedReport();
});

$container->bind('MemoryReport', function () {
    return new MemoryReport();
});

$container->tag(['SpeedReport', 'MemoryReport'], 'reports');

// Resolve all services with the 'reports' tag
$reports = $container->tagged('reports');
```

### Extending Resolved Objects

[](#extending-resolved-objects)

You can extend a resolved object to add additional functionality:

```
$container->bind('logger', function () {
    return new FileLogger();
});

$container->extend('logger', function ($logger, $container) {
    return new LogDecorator($logger);
});
```

### Method Invocation with Dependency Injection

[](#method-invocation-with-dependency-injection)

The container can call methods with automatic dependency injection:

```
$result = $container->call([$controller, 'show'], ['id' => 1]);

// Using Class@method syntax
$result = $container->call('UserController@show', ['id' => 1]);
```

Working with Swoole Coroutines
------------------------------

[](#working-with-swoole-coroutines)

When working with Swoole's coroutines, you might need to scope certain bindings to the current coroutine:

```
// Register a scoped binding
$container->scoped('database.connection', function ($container) {
    return new DbConnection($container->make('config'));
});

// Clear scoped instances between requests
$container->forgetScopedInstances();
```

API Reference
-------------

[](#api-reference)

### Container Methods

[](#container-methods)

#### Binding

[](#binding-1)

- `bind($abstract, $concrete = null, $shared = false)`: Register a binding with the container
- `singleton($abstract, $concrete = null)`: Register a shared binding
- `scoped($abstract, $concrete = null)`: Register a binding scoped to the current coroutine
- `instance($abstract, $instance)`: Register an existing instance as shared
- `extend($abstract, Closure $closure)`: Extend a resolved instance
- `bindIf($abstract, $concrete = null, $shared = false)`: Register a binding if not already registered
- `singletonIf($abstract, $concrete = null)`: Register a shared binding if not already registered
- `scopedIf($abstract, $concrete = null)`: Register a scoped binding if not already registered

#### Resolving

[](#resolving-1)

- `make($abstract, array $parameters = [])`: Resolve a type from the container
- `get($id)`: Resolve a type from the container (PSR-11 compatible)
- `build($concrete)`: Instantiate a concrete instance of a class
- `factory($abstract)`: Get a closure to resolve the given type
- `call($callback, array $parameters = [], $defaultMethod = null)`: Call a method with dependency injection

#### Alias and Tagging

[](#alias-and-tagging)

- `alias($abstract, $alias)`: Alias a type to a different name
- `tag($abstracts, $tags)`: Assign tags to bindings
- `tagged($tag)`: Resolve all bindings for a tag

#### Contextual Binding

[](#contextual-binding-1)

- `when($concrete)`: Define a contextual binding
- `addContextualBinding($concrete, $abstract, $implementation)`: Add a contextual binding

#### Lifecycle Events

[](#lifecycle-events)

- `resolving($abstract, Closure $callback = null)`: Register a resolving callback
- `afterResolving($abstract, Closure $callback = null)`: Register an after resolving callback
- `beforeResolving($abstract, Closure $callback = null)`: Register a before resolving callback

#### Container Management

[](#container-management)

- `flush()`: Clear all bindings and resolved instances
- `forgetInstance($abstract)`: Remove a resolved instance
- `forgetInstances()`: Clear all resolved instances
- `forgetScopedInstances()`: Clear all scoped instances
- `bound($abstract)`: Check if a binding exists
- `resolved($abstract)`: Check if a type has been resolved
- `has($id)`: Check if a binding exists (PSR-11 compatible)

### ContextualBindingBuilder Methods

[](#contextualbindingbuilder-methods)

- `needs($abstract)`: Define the abstract target that depends on the context
- `give($implementation)`: Define the implementation for the contextual binding
- `giveTagged($tag)`: Define tagged services to use as the implementation
- `giveConfig($key, $default = null)`: Define a configuration value to use as the implementation

Exception Handling
------------------

[](#exception-handling)

The container throws various exceptions in different scenarios:

- `BindingResolutionException`: Thrown when a concrete cannot be built or resolved
- `CircularDependencyException`: Thrown when circular dependencies are detected
- `EntryNotFoundException`: Thrown when a binding is not found (implements PSR-11)

Integration with ODY Framework
------------------------------

[](#integration-with-ody-framework)

The `ContainerHelper` class provides utility methods for integrating the container with the ODY framework:

```
use Ody\Container\Container;
use Ody\Container\ContainerHelper;

$container = new Container();
$config = require 'config/app.php';

// Configure the application container with basic services
$container = ContainerHelper::configureContainer($container, $config);

// Register all controllers in a directory
ContainerHelper::registerControllers($container, __DIR__ . '/app/Controllers');
```

License
-------

[](#license)

The ODY Container is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance46

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity56

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

Every ~23 days

Total

2

Last Release

405d ago

Major Versions

0.1.0 → 1.0.02025-04-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/984734252c6b932be5ef737920c3d0f792283664e75ba405f3df268cc1da138c?d=identicon)[IlyasDeckers](/maintainers/IlyasDeckers)

---

Top Contributors

[![IlyasDeckers](https://avatars.githubusercontent.com/u/18727603?v=4)](https://github.com/IlyasDeckers "IlyasDeckers (12 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laravel/framework

The Laravel Framework.

34.6k509.9M17.0k](/packages/laravel-framework)[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[cakephp/cache

Easy to use Caching library with support for multiple caching backends

498.5M16](/packages/cakephp-cache)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)

PHPackages © 2026

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