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

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

shopie/di-container
===================

IoC Container

v2.1.2(4mo ago)06282MITPHPPHP ^8.4

Since Dec 17Pushed 4mo agoCompare

[ Source](https://github.com/Shopie-App/di-container)[ Packagist](https://packagist.org/packages/shopie/di-container)[ RSS](/packages/shopie-di-container/feed)WikiDiscussions master Synced today

READMEChangelog (5)DependenciesVersions (7)Used By (2)

DI Container
============

[](#di-container)

Simple IoC container for PHP.

- **Lazy loading**: Services are only instantiated when requested.
- **Auto-wiring**: Automatically resolves constructor dependencies.
- **Separation of concerns**: Distinct `ServiceCollection` (configuration) and `ServiceProvider` (resolution).
- **Lifecycle management**: Supports Scoped (singleton per provider) and Ephemeral (factory) lifecycles.

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

[](#installation)

```
composer require shopie/di-container
```

Usage
-----

[](#usage)

### Basic Setup

[](#basic-setup)

The container is split into two parts:

1. `ServiceCollection`: Where you register your services.
2. `ServiceProvider`: Where you retrieve your services.

```
use Shopie\DiContainer\ServiceCollection;
use Shopie\DiContainer\ServiceProvider;

// 1. Create the collection
$collection = new ServiceCollection();

// 2. Register services
$collection->add(MyService::class);

// 3. Create the provider
$provider = new ServiceProvider($collection);

// 4. Resolve a service
$service = $provider->getService(MyService::class);
```

### Binding Interfaces to Implementations

[](#binding-interfaces-to-implementations)

You can bind an interface or abstract class to a specific concrete implementation.

```
use Shopie\DiContainer\ServiceCollection;

$collection = new ServiceCollection();

// When 'LoggerInterface' is requested, provide 'FileLogger'
$collection->add(LoggerInterface::class, FileLogger::class);
```

### Service Lifecycles

[](#service-lifecycles)

There are two types of service lifecycles:

- **Scoped (Default)**: The instance is created once and reused for subsequent requests within the same `ServiceProvider` instance.
- **Ephemeral**: A new instance is created every time it is requested.

```
use Shopie\DiContainer\Contracts\ServiceCollectionInterface;

// Scoped (Default)
$collection->add(DatabaseConnection::class);

// Ephemeral
$collection->add(
    RandomNumberGenerator::class,
    null,
    ServiceCollectionInterface::TYPE_EPHEMERAL
);
```

### Using Closures (Factories)

[](#using-closures-factories)

You can use a closure to manually construct a service. This is useful for configuration or complex initialization.

```
$collection->add(ApiClient::class, function (ServiceProvider $provider) {
    $apiKey = getenv('API_KEY');
    return new ApiClient($apiKey);
});
```

### Auto-wiring Dependencies

[](#auto-wiring-dependencies)

The container automatically resolves dependencies defined in the constructor.

```
class UserController
{
    public function __construct(private UserRepository $repo) {}
}

// Register both
$collection->add(UserRepository::class);
$collection->add(UserController::class);

// UserController will be instantiated with UserRepository injected automatically
$controller = $provider->getService(UserController::class);
```

### Resetting Services (Persistent Environments)

[](#resetting-services-persistent-environments)

In persistent environments like Swoole, RoadRunner, or FrankenPHP, services are often reused across requests. To prevent data leakage (e.g., user context, database connections), you can implement the ResettableInterface.

1. Implement ResettableInterface in your service:

```
use Shopie\DiContainer\Contracts\ResettableInterface;

class UserService implements ResettableInterface
{
    public function reset(): void
    {
        // Reset state for the next request
        $this->currentUser = null;
    }
}
```

2. Call resetAll() on the collection at the end of the request lifecycle:

```
// After the request is handled
$collection->resetAll();
```

### Manual Injection (Testing)

[](#manual-injection-testing)

You can manually inject an instantiated object into the container using setObject. This is useful for testing (injecting mocks) or when bridging with other containers.

Note: The service must be registered first.

```
// Register the service first
$collection->add(MyService::class);

// Inject the instance
$mock = new MockService();
$collection->setObject(MyService::class, $mock);

### Removing Services
You can remove a service definition and its instance from the collection at runtime.

```php
$collection->remove(MyService::class);
```

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance74

Regular maintenance activity

Popularity16

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity64

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

Recently: every ~38 days

Total

6

Last Release

145d ago

Major Versions

v1.0.1 → v2.0.02026-02-06

PHP version history (2 changes)v1.0.0PHP ^8.2

v2.0.0PHP ^8.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3966200?v=4)[shopie](/maintainers/shopie)[@shopie](https://github.com/shopie)

---

Top Contributors

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

### Embed Badge

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

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

###  Alternatives

[motomedialab/laravel-vite-helper

A helper method to generate absolute asset URL's to Vite assets

30587.0k2](/packages/motomedialab-laravel-vite-helper)[lootils/uuid

A simple class for working with UUIDs.

3383.3k](/packages/lootils-uuid)

PHPackages © 2026

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