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

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

phpdot/container-swoole
=======================

Swoole context provider and per-request dispatcher for phpdot/container

v0.1.0(4w ago)00MITPHPPHP &gt;=8.5

Since Jul 18Pushed 4w agoCompare

[ Source](https://github.com/phpdot/container-swoole)[ Packagist](https://packagist.org/packages/phpdot/container-swoole)[ RSS](/packages/phpdot-container-swoole/feed)WikiDiscussions main Synced 6d ago

READMEChangelogDependencies (33)Versions (8)Used By (0)

phpdot/container-swoole
=======================

[](#phpdotcontainer-swoole)

Swoole adapter for [phpdot/container](https://github.com/phpdot/container).

Each Swoole coroutine gets its own isolated service scope via `Coroutine::getContext()`. When the coroutine exits, Swoole destroys the context automatically — no manual cleanup required.

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [How It Works](#how-it-works)
- [Server Example](#server-example)
- [Request dispatching](#request-dispatching)
- [Architecture](#architecture)
- [Testing](#testing)
- [License](#license)

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

[](#requirements)

RequirementConstraintPHP`>= 8.5`ext-swoole`>= 6.2``phpdot/container``^0.1``phpdot/contracts``^0.1``psr/container``^1.1 || ^2.0``psr/http-message``^2.0``psr/http-server-handler``^1.0`Installation
------------

[](#installation)

```
composer require phpdot/container-swoole
```

Usage
-----

[](#usage)

```
use PHPdot\Container\ContainerBuilder;
use PHPdot\Container\Swoole\SwooleContextProvider;
use function PHPdot\Container\singleton;
use function PHPdot\Container\scoped;

$container = (new ContainerBuilder())
    ->withContextProvider(new SwooleContextProvider())
    ->addDefinitions([
        // Shared across all coroutines
        Router::class  => singleton(),
        Redis::class   => singleton(),

        // Isolated per coroutine — fresh for each request
        Session::class       => scoped(),
        SignalManager::class => scoped(),
    ])
    ->build();
```

How It Works
------------

[](#how-it-works)

```
┌──────────────────────────────────────────────────────────┐
│ Swoole Worker                                            │
│                                                          │
│  Singletons (shared)                                     │
│  ┌────────────────────────────────────────────────────┐  │
│  │  Router       Redis       Config      LogBridge    │  │
│  └────────────────────────────────────────────────────┘  │
│                                                          │
│  Coroutine 1              Coroutine 2                    │
│  ┌──────────────────┐    ┌──────────────────┐           │
│  │ Session (User A)  │    │ Session (User B)  │           │
│  │ Signal (trace-1)  │    │ Signal (trace-2)  │           │
│  └──────────────────┘    └──────────────────┘           │
│    auto-destroyed           auto-destroyed               │
│    on coroutine exit        on coroutine exit             │
└──────────────────────────────────────────────────────────┘

```

**Singleton** services resolve once and are shared across all coroutines in the worker.

**Scoped** services resolve once per coroutine and are stored in `Swoole\Coroutine::getContext()`. When the coroutine finishes, Swoole's runtime destroys the context and all scoped instances are garbage collected.

**Outside a coroutine** (CLI bootstrap, `onStart` callback), the provider falls back to an in-memory `ArrayContext`.

Server Example
--------------

[](#server-example)

```
use Swoole\Http\Server;
use PHPdot\Container\ContainerBuilder;
use PHPdot\Container\Swoole\SwooleContextProvider;
use function PHPdot\Container\singleton;
use function PHPdot\Container\scoped;

$container = (new ContainerBuilder())
    ->withContextProvider(new SwooleContextProvider())
    ->addDefinitions([
        Config::class  => singleton(),
        Session::class => scoped(fn($c) => Session::fromRequest($c->get(Request::class))),
    ])
    ->build();

$server = new Server('0.0.0.0', 8080);

$server->on('request', function ($req, $res) use ($container) {
    // Each request runs in its own coroutine.
    // Scoped services are fresh. Singletons are shared.
    $session = $container->get(Session::class);

    $res->end('Hello ' . $session->user());
    // Coroutine ends here — scoped instances destroyed automatically.
});

$server->start();
```

Request dispatching
-------------------

[](#request-dispatching)

`ContainerDispatcher` is a PSR-15 handler that resolves your real handler from the container **on every request** — inside the worker, after the fork. Serve it instead of the handler itself so the request path loads lazily (which keeps it hot-reloadable) and scoped services isolate per coroutine:

```
use PHPdot\Container\Swoole\ContainerDispatcher;

// $container built as above; App\Handler is your PSR-15 entry point.
$dispatcher = new ContainerDispatcher($container, App\Handler::class);

// Hand $dispatcher to your PSR-15 server (e.g. phpdot/server-swoole's serve()).
// On each request it calls $container->get(App\Handler::class) — resolving,
// and loading, in the worker.
```

If the configured id doesn't resolve to a `Psr\Http\Server\RequestHandlerInterface`, it throws — a fast failure for a misconfigured handler id.

Architecture
------------

[](#architecture)

 ```
graph TD
    REQ["Incoming requestone Swoole coroutine each"]
    DISP["ContainerDispatcherPSR-15 handler: opens a freshper-request scope, runs the inner handler"]
    CONTAINER["phpdot/containerresolves scoped servicesthrough the active context"]
    PROV["SwooleContextProviderContracts ContextProviderInterface,backed by Swoole\Coroutine::getContext()"]
    CTX["SwooleContextContext + ContextDestroy: per-coroutinescoped-instance store, freed at coroutine end"]

    REQ --> DISP
    DISP --> CONTAINER
    CONTAINER --> PROV
    PROV --> CTX
```

      Loading Testing
-------

[](#testing)

The package is standalone-testable (requires ext-swoole):

```
composer install
composer test        # PHPUnit
composer analyse     # PHPStan, level max + strict rules
composer cs-check    # PHP-CS-Fixer
composer check       # All three
```

License
-------

[](#license)

MIT.

**This repository is a read-only mirror**, generated by CI from [phpdot/monorepo](https://github.com/phpdot/monorepo). [Pull requests](https://github.com/phpdot/monorepo/pulls)and [issues](https://github.com/phpdot/monorepo/issues) belong in the monorepo.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance94

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80% 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 ~18 days

Total

7

Last Release

28d ago

PHP version history (3 changes)v1.0.0PHP &gt;=8.3

v1.3.1PHP &gt;=8.4

v0.1.0PHP &gt;=8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/62e82421bda4b5d6ba9a47ba6d88caca060dcd0d1a2862f351f3a97657385db0?d=identicon)[phpdot](/maintainers/phpdot)

---

Top Contributors

[![phpdot](https://avatars.githubusercontent.com/u/252500?v=4)](https://github.com/phpdot "phpdot (4 commits)")[![o3AM](https://avatars.githubusercontent.com/u/252500?v=4)](https://github.com/o3AM "o3AM (1 commits)")

---

Tags

containerContextswoolecoroutinescope

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.4M2.2k](/packages/symfony-symfony)[cakephp/cakephp

The CakePHP framework

8.9k20.0M1.8k](/packages/cakephp-cakephp)[bref/bref

Bref is a framework to write and deploy serverless PHP applications on AWS Lambda.

3.4k11.0M74](/packages/bref-bref)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k20](/packages/tempest-framework)[moonshine/moonshine

Laravel administration panel

1.3k268.2k88](/packages/moonshine-moonshine)

PHPackages © 2026

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