PHPackages                             tourze/workerman-connection-context - 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. tourze/workerman-connection-context

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

tourze/workerman-connection-context
===================================

Workerman连接上下文管理包，提供线程安全的连接级别上下文存储

0.0.3(6mo ago)0822MITPHPCI passing

Since Jun 18Pushed 6mo agoCompare

[ Source](https://github.com/tourze/workerman-connection-context)[ Packagist](https://packagist.org/packages/tourze/workerman-connection-context)[ RSS](/packages/tourze-workerman-connection-context/feed)WikiDiscussions master Synced 1mo ago

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

Workerman Connection Context
============================

[](#workerman-connection-context)

[![PHP Version](https://camo.githubusercontent.com/ef363a5a30025ffef1857918c40fa01e97f03929e5f87d12a14bf334a7de9220/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d3838393242462e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/07c5a0015c097e0dfbb44d4220df0eed6a623d83eceb02ac299fe96b8e4e1a73/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f63692e796d6c3f6272616e63683d6d6173746572)](https://github.com/tourze/php-monorepo/actions)[![Code Coverage](https://camo.githubusercontent.com/9cb168340a6d5a1bdda8e16dafe8eed3d60f1441986fb63de17bff84ee6a18f0/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f)](https://codecov.io/gh/tourze/php-monorepo)

[English](README.md) | [中文](README.zh-CN.md)

A context management solution for Workerman connections. This package provides a way to store and manage connection-specific context objects using PHP's WeakMap feature for automatic memory management.

Features
--------

[](#features)

- Connection-specific context storage
- Multiple context types per connection
- Automatic cleanup using WeakMap
- Type-safe context retrieval
- Singleton pattern for global access

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

[](#installation)

```
composer require tourze/workerman-connection-context
```

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

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Tourze\Workerman\ConnectionContext\ContextContainer;

// Define your context class
class UserContext
{
    public function __construct(
        private string $userId,
        private array $permissions
    ) {}

    public function getUserId(): string
    {
        return $this->userId;
    }

    public function getPermissions(): array
    {
        return $this->permissions;
    }
}

// In your Workerman callback
$worker->onConnect = function ($connection) {
    $context = new UserContext('user123', ['read', 'write']);
    ContextContainer::getInstance()->setContext($connection, $context);
};

$worker->onMessage = function ($connection, $data) {
    $context = ContextContainer::getInstance()->getContext($connection, UserContext::class);
    if ($context) {
        echo "User: " . $context->getUserId() . "\n";
        echo "Permissions: " . implode(', ', $context->getPermissions()) . "\n";
    }
};
```

### Multiple Context Types

[](#multiple-context-types)

```
class SessionContext
{
    public function __construct(private string $sessionId) {}

    public function getSessionId(): string
    {
        return $this->sessionId;
    }
}

class AuthContext
{
    public function __construct(private bool $isAuthenticated) {}

    public function isAuthenticated(): bool
    {
        return $this->isAuthenticated;
    }
}

// Store multiple context types for the same connection
$sessionContext = new SessionContext('sess_123');
$authContext = new AuthContext(true);

ContextContainer::getInstance()->setContext($connection, $sessionContext);
ContextContainer::getInstance()->setContext($connection, $authContext);

// Retrieve specific context types
$session = ContextContainer::getInstance()->getContext($connection, SessionContext::class);
$auth = ContextContainer::getInstance()->getContext($connection, AuthContext::class);
```

### Context Cleanup

[](#context-cleanup)

```
// Clear specific context type
ContextContainer::getInstance()->clearContext($connection, UserContext::class);

// Clear all contexts for a connection
ContextContainer::getInstance()->clearAllContexts($connection);
```

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

[](#api-reference)

### ContextContainer

[](#contextcontainer)

#### `getInstance(): ContextContainer`

[](#getinstance-contextcontainer)

Get the singleton instance of the context container.

#### `setContext(ConnectionInterface $connection, object $context): void`

[](#setcontextconnectioninterface-connection-object-context-void)

Store a context object for the specified connection.

#### `getContext(ConnectionInterface $connection, string $className): ?object`

[](#getcontextconnectioninterface-connection-string-classname-object)

Retrieve a context object of the specified type for the connection.

#### `clearContext(ConnectionInterface $connection, string $className): void`

[](#clearcontextconnectioninterface-connection-string-classname-void)

Remove a specific context type for the connection.

#### `clearAllContexts(ConnectionInterface $connection): void`

[](#clearallcontextsconnectioninterface-connection-void)

Remove all context objects for the connection.

Memory Management
-----------------

[](#memory-management)

This package uses PHP's WeakMap to automatically clean up context data when connection objects are garbage collected. This prevents memory leaks in long-running Workerman applications.

License
-------

[](#license)

MIT License

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance67

Regular maintenance activity

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity28

Early-stage or recently created project

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

Total

3

Last Release

200d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-workerman-connection-context/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-workerman-connection-context/health.svg)](https://phpackages.com/packages/tourze-workerman-connection-context)
```

###  Alternatives

[nativephp/mobile

NativePHP for Mobile

82724.0k43](/packages/nativephp-mobile)[joanhey/adapterman

Use any framework and application with Workerman.

85255.9k1](/packages/joanhey-adapterman)[topthink/think-worker

workerman extend for thinkphp

202227.2k9](/packages/topthink-think-worker)[workerman/crontab

A crontab written in PHP based on workerman

70164.2k58](/packages/workerman-crontab)[workerman/globaldata

8164.2k16](/packages/workerman-globaldata)[workerman/coroutine

Workerman coroutine

15260.0k6](/packages/workerman-coroutine)

PHPackages © 2026

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