PHPackages                             ody/server - 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/server

ActiveLibrary[Framework](/categories/framework)

ody/server
==========

Swoole HTTP server for ODY framework

0.2.0(1y ago)1292MITPHPPHP &gt;=8.3CI failing

Since Mar 16Pushed 1y ago1 watchersCompare

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

READMEChangelog (7)Dependencies (7)Versions (9)Used By (2)

[![Actions Status](https://github.com/ody-dev/ody-http-server/workflows/Build%20and%20test/badge.svg)](https://github.com/ody-dev/ody-http-server/actions)[![License](https://camo.githubusercontent.com/8f54ef1c824012d2ab1171de1e7e380a27729f72102a10d0fef373bfe4b786cd/68747470733a2f2f706f7365722e707567782e6f72672f6f64792f636f72652f6c6963656e7365)](https://packagist.org/packages/ody/core)

Ody Server
==========

[](#ody-server)

Ody Server is a package for the Ody PHP framework that provides high-performance HTTP server capabilities powered by Swoole. It offers easy server management with command-line tools, hot-reloading support, and administrative features.

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

[](#table-of-contents)

- [Introduction](#introduction)
- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Configuration](#configuration)
- [Server Management](#server-management)
- [Server Events](#server-events)
- [Admin Server](#admin-server)
- [API Reference](#api-reference)

Introduction
------------

[](#introduction)

Ody Server simplifies the process of creating and managing Swoole-based servers. It provides:

- Command-line tools for managing server processes
- HTTP, WebSocket, and TCP server support
- Hot reloading capabilities for development
- Server state management
- Administrative API interface for monitoring and management

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

[](#installation)

```
composer require ody-dev/server
```

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

[](#basic-usage)

### Starting a Server

[](#starting-a-server)

To start a server, use the `server:start` command:

```
php ody server:start
```

Options:

- `--daemonize` or `-d`: Run the server in the background
- `--watch` or `-w`: Enable file watching for hot reloading

### Stopping a Server

[](#stopping-a-server)

To stop a running server:

```
php ody server:stop
```

### Reloading a Server

[](#reloading-a-server)

To reload workers without stopping the server:

```
php ody server:reload
```

Configuration
-------------

[](#configuration)

Server configuration should be defined in your application's `config/server.php` file:

```
return [
    // Server host
    'host' => env('SERVER_HOST', '127.0.0.1'),

    // Server port
    'port' => env('SERVER_PORT', 9501),

    // Server mode (SWOOLE_BASE or SWOOLE_PROCESS)
    'mode' => SWOOLE_PROCESS,

    // Socket type
    'sock_type' => SWOOLE_SOCK_TCP,

    // SSL configuration
    'ssl' => [
        'ssl_cert_file' => env('SSL_CERT_FILE', null),
        'ssl_key_file' => env('SSL_KEY_FILE', null),
    ],

    // Additional Swoole server settings
    'additional' => [
        'worker_num' => env('SERVER_WORKER_NUM', 4),
        'task_worker_num' => env('SERVER_TASK_WORKER_NUM', 2),
        'reactor_num' => env('SERVER_REACTOR_NUM', 2),
        'max_request' => 1000,
        'buffer_output_size' => 2 * 1024 * 1024,
        'admin_server' => '127.0.0.1:9506',
    ],

    // Server event callbacks
    'callbacks' => [
        'start' => [\Ody\Server\ServerCallbacks::class, 'onStart'],
        'workerStart' => [\Ody\Server\ServerCallbacks::class, 'onWorkerStart'],
        'managerStart' => [\Ody\Server\ServerCallbacks::class, 'onManagerStart'],
        'managerStop' => [\Ody\Server\ServerCallbacks::class, 'onManagerStop'],
        'request' => [\Ody\Server\ServerCallbacks::class, 'onRequest'],
        'workerError' => [\Ody\Server\ServerCallbacks::class, 'onWorkerError'],
        // Add additional callbacks as needed
    ],

    // File paths to watch for hot reloading (when --watch is enabled)
    'watch_paths' => [
        'app/',
        'config/',
        'routes/',
    ],
];
```

Server Management
-----------------

[](#server-management)

The `ServerManager` class provides an interface for creating and managing Swoole servers.

```
use Ody\Server\ServerManager;
use Ody\Server\ServerType;
use Ody\Server\State\HttpServerState;

// Initialize the server manager
$serverManager = ServerManager::init(ServerType::HTTP_SERVER)
    ->createServer($config)
    ->setServerConfig($additionalConfig)
    ->registerCallbacks($callbacks)
    ->daemonize($daemonize);

// Get the server instance
$server = $serverManager->getServerInstance();

// Start the server
Server::start($server);
```

Server Events
-------------

[](#server-events)

The following server events can be registered in your configuration:

EventDescription`ON_START`Triggered when the server starts`ON_WORKER_START`Triggered when a worker process starts`ON_WORKER_STOP`Triggered when a worker process stops`ON_WORKER_EXIT`Triggered when a worker process exits`ON_WORKER_ERROR`Triggered when a worker process encounters an error`ON_PIPE_MESSAGE`Triggered when a message is sent through pipes`ON_REQUEST`Triggered when an HTTP request is received`ON_RECEIVE`Triggered when data is received`ON_CONNECT`Triggered when a client connects`ON_DISCONNECT`Triggered when a client disconnects`ON_OPEN`Triggered when a WebSocket connection is opened`ON_MESSAGE`Triggered when a WebSocket message is received`ON_CLOSE`Triggered when a connection is closed`ON_TASK`Triggered when a task is received`ON_FINISH`Triggered when a task is finished`ON_SHUTDOWN`Triggered when the server shuts down`ON_PACKET`Triggered when a UDP packet is received`ON_MANAGER_START`Triggered when the manager process starts`ON_MANAGER_STOP`Triggered when the manager process stops`ON_BEFORE_START`Triggered before the server starts (not a Swoole event)Server State
------------

[](#server-state)

The `HttpServerState` class manages the state of running server processes, allowing for tracking and management of processes.

```
$serverState = HttpServerState::getInstance();

// Check if the server is running
if ($serverState->httpServerIsRunning()) {
    // Server is running
}

// Get process IDs
$masterPid = $serverState->getMasterProcessId();
$managerPid = $serverState->getManagerProcessId();
$workerPids = $serverState->getWorkerProcessIds();

// Kill processes
$serverState->killProcesses([
    $masterPid,
    $managerPid,
    // ...worker PIDs
]);

// Reload processes
$serverState->reloadProcesses([
    $masterPid,
    $managerPid,
    // ...worker PIDs
]);

// Clear process IDs
$serverState->clearProcessIds();
```

Admin Server
------------

[](#admin-server)

!! Use with caution, very experimental and likely to break !!

The `AdminServer` class provides an administrative interface for monitoring and managing Swoole servers. It exposes a RESTful API for interacting with the server processes.

To enable the Admin server, add the following to your server configuration:

```
'additional' => [
    // ...
    'admin_server' => '127.0.0.1:9502',
    // ...
],
```

You can access a web-based dashboard at `http://your-admin-server:port/dashboard`.

### Authentication

[](#authentication)

The admin server supports authentication via the `admin_server` URI:

```
username:password@host:port

```

When authenticated, an access token is generated as `sha1(username . password)` and must be provided in the `X-ADMIN-SERVER-ACCESS-TOKEN` HTTP header.

### API Endpoints

[](#api-endpoints)

The admin server exposes a RESTful API at the `/api` endpoint. The URL structure is:

```
/api/COMMAND/PROCESS

```

Where:

- `COMMAND` is one of the registered command names
- `PROCESS` identifies the target process (e.g., "master", "worker-0", "all")

#### Available Commands

[](#available-commands)

CommandDescriptionHTTP Method`server_reload`Reload worker processesPOST`server_shutdown`Shut down the serverPOST`server_stats`Get server statisticsGET`server_setting`Get server configurationGET`coroutine_stats`Get coroutine statisticsGET`coroutine_list`Get active coroutinesGET`coroutine_bt`Get coroutine backtracePOST`get_version_info`Get version informationGET`get_worker_info`Get worker process informationGET`get_timer_list`Get active timersGET`get_server_memory_usage`Get memory usageGET`get_server_cpu_usage`Get CPU usageGET`close_session`Close a client connectionPOST`get_client_info`Get client informationGET#### Example Requests

[](#example-requests)

Retrieve server statistics:

```
GET /api/server_stats/master

```

Reload the server:

```
POST /api/server_reload/master

```

Get coroutine list from all worker processes:

```
GET /api/coroutine_list/all_worker

```

Close a client connection:

```
POST /api/close_session/worker-0
{
  "session_id": 1
}

```

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

[](#api-reference)

### Server Types

[](#server-types)

The `ServerType` class provides constants for different server types:

- `HTTP_SERVER`: Swoole HTTP server (`\Swoole\Http\Server`)
- `WS_SERVER`: Swoole WebSocket server (`\Swoole\WebSocket\Server`)
- `TCP_SERVER`: Swoole TCP server (`\Swoole\Server`)

### Server Events

[](#server-events-1)

The `ServerEvent` class provides constants for all supported server events:

- `ON_START`: Server start event
- `ON_WORKER_START`: Worker process start event
- `ON_WORKER_STOP`: Worker process stop event
- `ON_WORKER_EXIT`: Worker process exit event
- `ON_WORKER_ERROR`: Worker process error event
- `ON_PIPE_MESSAGE`: Pipe message event
- `ON_REQUEST`: HTTP request event
- `ON_RECEIVE`: Data receive event
- `ON_CONNECT`: Client connect event
- `ON_DISCONNECT`: Client disconnect event
- `ON_OPEN`: WebSocket open event
- `ON_MESSAGE`: WebSocket message event
- `ON_CLOSE`: Connection close event
- `ON_TASK`: Task event
- `ON_FINISH`: Task finish event
- `ON_SHUTDOWN`: Server shutdown event
- `ON_PACKET`: UDP packet event
- `ON_MANAGER_START`: Manager start event
- `ON_MANAGER_STOP`: Manager stop event
- `ON_BEFORE_START`: Before server start event (not a Swoole event)

### ServerManager Class

[](#servermanager-class)

Methods:

- `init(string $serverType): static` - Initialize the server manager with a server type
- `createServer(?array $config): static` - Create a new server instance with the given configuration
- `setServerConfig(array $config): static` - Set additional server configuration
- `getServerInstance(): HttpServer|WsServer` - Get the server instance
- `registerCallbacks(array $callbacks): static` - Register event callbacks
- `setWatcher(int $enableWatcher, array $paths, object $serverState): static` - Enable file watching for hot reloading
- `daemonize(bool $daemonize): static` - Set the server to run in the background
- `setLogger(LoggerInterface $logger): self` - Set the logger instance
- `setConfig(Config $config): self` - Set the configuration instance
- `start(): void` - Start the server

### ServerState Class

[](#serverstate-class)

Methods:

- `getInstance(): self` - Get the singleton instance
- `getInformation(): array` - Get the state information
- `setManagerProcessId(?int $id): void` - Set the manager process ID
- `setMasterProcessId(?int $id): void` - Set the master process ID
- `setWatcherProcessId(?int $id): void` - Set the watcher process ID
- `setWorkerProcessIds(array $ids): void` - Set the worker process IDs
- `getManagerProcessId(): int|null` - Get the manager process ID
- `getMasterProcessId(): int|null` - Get the master process ID
- `getWatcherProcessId(): int|null` - Get the watcher process ID
- `getWorkerProcessIds(): array` - Get the worker process IDs
- `clearProcessIds(): void` - Clear all process IDs
- `reloadProcesses(array $processIds): void` - Reload the specified processes
- `killProcesses(array $processIds): void` - Kill the specified processes

### HttpServerState Class

[](#httpserverstate-class)

Methods:

- `getInstance(): self` - Get the singleton instance
- `httpServerIsRunning(): bool` - Check if the HTTP server is running

### AdminServer Class

[](#adminserver-class)

Methods:

- `init(Server $server): void` - Initialize the admin server
- `getAccessToken(): string` - Get the access token
- `start(Server $server): void` - Start the admin server

### ServerCallbacks Class

[](#servercallbacks-class)

Static methods:

- `onStart(SwServer $server): void` - Handle server start event
- `onRequest(SwRequest $request, SwResponse $response): void` - Handle HTTP request event
- `onWorkerStart(SwServer $server, int $workerId): void` - Handle worker start event
- `onManagerStart(SwServer $server)` - Handle manager start event
- `onManagerStop(SwServer $server)` - Handle manager stop event
- `onReceive(SwServer $server, int $fd, int $reactorId, string $data)` - Handle data receive event
- `onWorkerError(SwServer $server, int $workerId, int $workerPid, int $exitCode, int $signal): void` - Handle worker error event

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance46

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity48

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

Total

7

Last Release

407d ago

### 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 (75 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

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

Authentication plugin for CakePHP

1153.6M67](/packages/cakephp-authentication)[neos/flow

Flow Application Framework

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

Authorization abstraction layer plugin for CakePHP

742.2M34](/packages/cakephp-authorization)[yiisoft/yii-middleware

Yii Middleware

21151.3k1](/packages/yiisoft-yii-middleware)[brandembassy/slim-nette-extension

19190.2k](/packages/brandembassy-slim-nette-extension)

PHPackages © 2026

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