PHPackages                             lighthouse/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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. lighthouse/container

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

lighthouse/container
====================

PSR-11 Dependency Injection Container for the Lighthouse framework

v0.1.0(6mo ago)0111MITPHPPHP ^8.2CI passing

Since Dec 17Pushed 6mo agoCompare

[ Source](https://github.com/RichardTrujilloTorres/container)[ Packagist](https://packagist.org/packages/lighthouse/container)[ RSS](/packages/lighthouse-container/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (4)Versions (2)Used By (1)

Lighthouse Container
====================

[](#lighthouse-container)

A PSR-11 compliant Dependency Injection Container for the Lighthouse framework.

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

[](#installation)

```
composer require lighthouse/container
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher

Features
--------

[](#features)

- Full PSR-11 compliance
- Autowiring via reflection
- Manual bindings
- Singletons
- Factories
- Interface to implementation binding
- Method injection
- Circular dependency detection

Quick Start
-----------

[](#quick-start)

### Basic Autowiring

[](#basic-autowiring)

The container can automatically resolve class dependencies:

```
use Lighthouse\Container\Container;

class Logger
{
    public function log(string $message): void
    {
        echo $message;
    }
}

class UserService
{
    public function __construct(
        private Logger $logger
    ) {}
}

$container = new Container();

// Automatically resolves Logger dependency
$userService = $container->get(UserService::class);
```

### Manual Bindings

[](#manual-bindings)

Bind interfaces to implementations:

```
interface CacheInterface
{
    public function get(string $key): mixed;
}

class RedisCache implements CacheInterface
{
    public function get(string $key): mixed
    {
        // Redis implementation
    }
}

$container->bind(CacheInterface::class, RedisCache::class);

$cache = $container->get(CacheInterface::class);
// Returns instance of RedisCache
```

### Closure Bindings

[](#closure-bindings)

Use closures for complex instantiation:

```
$container->bind(Database::class, function (Container $c) {
    $config = $c->get(Config::class);

    return new Database(
        host: $config->get('db.host'),
        user: $config->get('db.user'),
        pass: $config->get('db.pass')
    );
});
```

### Singletons

[](#singletons)

Register a binding that returns the same instance:

```
$container->singleton(Database::class, function (Container $c) {
    return new Database(/* ... */);
});

$db1 = $container->get(Database::class);
$db2 = $container->get(Database::class);

// $db1 === $db2 (same instance)
```

### Register Existing Instance

[](#register-existing-instance)

```
$logger = new Logger();
$container->instance(Logger::class, $logger);

// Always returns the same $logger instance
```

### Factories

[](#factories)

Register a factory that creates a new instance each time:

```
$container->factory(RequestId::class, function () {
    return new RequestId(uniqid());
});

$id1 = $container->get(RequestId::class); // RequestId with unique id
$id2 = $container->get(RequestId::class); // Different RequestId
```

### Method Injection

[](#method-injection)

Call methods with automatic dependency resolution:

```
class OrderController
{
    public function store(OrderService $service, Validator $validator): Order
    {
        // ...
    }
}

$controller = new OrderController();

// Automatically resolves OrderService and Validator
$result = $container->call($controller, 'store');

// With additional parameters
$result = $container->call($controller, 'update', ['id' => 123]);
```

### PSR-11 Methods

[](#psr-11-methods)

```
// Check if entry exists
$container->has(Logger::class); // true/false

// Get entry (throws NotFoundException if not found)
$container->get(Logger::class);
```

Error Handling
--------------

[](#error-handling)

The container throws PSR-11 compliant exceptions:

```
use Lighthouse\Container\Exception\NotFoundException;
use Lighthouse\Container\Exception\ContainerException;

try {
    $container->get('UnknownClass');
} catch (NotFoundException $e) {
    // Entry not found
} catch (ContainerException $e) {
    // Error during resolution (circular dependency, etc.)
}
```

Circular Dependency Detection
-----------------------------

[](#circular-dependency-detection)

The container detects circular dependencies and throws a clear error:

```
class A {
    public function __construct(B $b) {}
}

class B {
    public function __construct(A $a) {}
}

$container->get(A::class);
// Throws: ContainerException: Circular dependency detected while resolving "A"
```

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

[](#api-reference)

MethodDescription`get(string $id)`Resolve an entry (PSR-11)`has(string $id)`Check if entry exists (PSR-11)`bind(string $id, mixed $concrete)`Register a binding`singleton(string $id, mixed $concrete)`Register a shared binding`instance(string $id, mixed $instance)`Register an existing instance`factory(string $id, callable $factory)`Register a factory`call(object|string $target, string $method, array $params)`Call method with DI`flush()`Clear all bindings and instances`getBindings()`Get all registered binding IDs`isShared(string $id)`Check if binding is a singletonTesting
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Part of the Lighthouse Framework
--------------------------------

[](#part-of-the-lighthouse-framework)

This package is part of the [Lighthouse Framework](https://github.com/lighthouse-php), an educational PHP framework designed to teach how modern frameworks work internally.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance66

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

198d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13813941?v=4)[Richard Trujillo](/maintainers/richardtrujillotorres)[@RichardTrujilloTorres](https://github.com/RichardTrujilloTorres)

---

Top Contributors

[![RichardTrujilloTorres](https://avatars.githubusercontent.com/u/13813941?v=4)](https://github.com/RichardTrujilloTorres "RichardTrujilloTorres (3 commits)")

---

Tags

containerPSR-11Autowiringdependency-injectiondiioclighthouse

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.9k55.5M1.2k](/packages/php-di-php-di)[slince/di

A flexible dependency injection container

20272.1k6](/packages/slince-di)

PHPackages © 2026

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