atlanticf / phpserver
Slight prefork multi-process text RPC server for PHP, Kubernetes-ready.
Requires
- php: >=8.3
- ext-pcntl: *
- ext-posix: *
- ext-sockets: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.5
Suggests
- ext-inotify: Local auto-reload on file change (dev only)
- psr/log: Optional. Adapt PhpServer\Log\LoggerInterface to a PSR-3 logger such as Monolog. Not required at runtime; see examples/psr3-logger-adapter.php.
Provides
None
Conflicts
None
Replaces
None
- dev-main / 1.1.x-dev
- v1.1.0
- v1.0.0
- dev-cursor/handler-discovery-watch-a791
- dev-cursor/release-1-1-0-a791
- dev-cursor/project-scaffold-docker-a791
- dev-cursor/composer-library-95e3
- dev-cursor/docs-english-95e3
- dev-cursor/agent-business-error-95e3
- dev-cursor/readme-rpc-example-95e3
- dev-cursor/benchmark-report-95e3
- dev-cursor/readme-github-standard-95e3
This package is auto-updated.
Last update: 2026-12-02 06:39:25 UTC
README
English · 简体中文
phpserver
Slight prefork text RPC server for Linux and Kubernetes. Library 1.1.0. Wire protocol text-rpc/1. The two versions are recorded separately and are not tied together.
This is a clean-room rewrite of the 2016 PHPServer idea: one master, preforked workers, a select loop, and two business hooks. It does not carry the old protocol, the old brand, or any runtime Composer package.
Contents
- About
- Features
- Requirements
- Install
- Quick start
- Usage
- Docker
- Kubernetes
- Documentation
- Development
- Provenance
- Contributing
- License
About
bin/serverd binds the listen socket, forks child_count workers, and drains on SIGTERM. Workers accept connections and run SelectLoop. Business code implements dealInput and dealProcess.
Admin probes and metrics listen on their own port, 127.0.0.1:9100 by default. Do not point /healthz or /readyz at the business port. Rate limiting is off unless a bootstrap calls setLimiter().
The documents under docs/ are in English.
Features
- Config: a PHP array file,
PHPSERVER_*overrides, checked before the process serves - Log: a
LoggerInterfacewith the same method names as PSR-3, text or JSON lines, request-id - Clock: wall time plus monotonic
hrtime - Protocol: text-rpc/1 frames (magic
TRPC/1) and a JSON body - Client: a blocking
Client, andbin/phpserver-rpc - Process:
bin/workerruns one foreground process;bin/serverdforks. Echo answers plaintexthello. The Rpc example speaks text-rpc/1 - Admin:
/healthz,/readyz,/status,/metricson the master - Runtime image and a Kubernetes example
Requirements
- PHP >= 8.3 (CI runs 8.3 and 8.4)
- Extensions:
pcntl,posix,sockets - Runtime Composer packages: none
Install
The package name is atlanticf/phpserver. PHP is >=8.3, with extensions pcntl, posix, and sockets. There are no runtime Composer packages.
| Autoload | Path | When |
|---|---|---|
PhpServer\ |
src/ |
always |
PhpServer\Examples\ |
examples/ |
always, so the sample Echo config loads with --no-dev |
PhpServer\Tests\ |
tests/ |
dev only |
Composer installs four binaries: vendor/bin/serverd, vendor/bin/worker, vendor/bin/phpserver-rpc, and vendor/bin/phpserver-init.
v1.1.0 is the first git tag whose composer.json names this package atlanticf/phpserver. The older tag v1.0.0 still names the package phpserver/phpserver, so it is not a release of this library. Do not composer require that old name: on Packagist it is a different 2018 project (bitbucket.org/phpserver/phpserver).
composer require atlanticf/phpserver:^1.1
There is no version field in composer.json. Composer reads the version from the git tag. dev-main stays aliased to 1.1.x-dev.
Quick start
Three commands, from the repository root. The third prints hello.
composer install php bin/serverd start --foreground -c config/server.echo.php
In another terminal:
curl -sS http://127.0.0.1:9000/
Stop the server with Ctrl-C.
Usage
Create a new service
Scaffold a ready-to-run business RPC service (code, config, tests, multi-stage Dockerfile, compose.yaml, and Kubernetes manifests) and install dependencies in one command. See docs/scaffolding.md.
On a Linux host (PHP >= 8.3 with pcntl, posix, sockets and Composer):
php bin/phpserver-init my-service
Or with Docker (no host PHP or Composer required):
docker run --rm -it -u "$(id -u):$(id -g)" -v "$PWD":/work -w /work \ ghcr.io/atlanticf/phpserver-base:php8.4-dev \ phpserver-init my-service
A small service
An RPC method is a string name plus a closure. Subclass RpcWorker so the class can be final, put the business method on a normal class, and register it from the bootstrap file. Do not override dealInput or dealProcess.
The project created by phpserver-init does this scan for you. bootstrap.php calls HandlerDiscovery on src/Handler. Add src/Handler/OrderApi.php with public function get(?array $params, string $traceId) and the method name is Order.get. A class whose name ends in Handler drops that suffix the same way. Restart the worker to pick up the new file.
AppWorker.php:
<?php declare(strict_types=1); namespace App; use PhpServer\Worker\RpcWorker; final class AppWorker extends RpcWorker {}
OrderApi.php. A normal return is the JSON result. A failure the caller can fix throws BusinessException. Any other exception stays -32603 with the message Internal error.
<?php declare(strict_types=1); namespace App; use PhpServer\Exception\AgentError; use PhpServer\Exception\BusinessException; final class OrderApi { /** @param array<array-key, mixed>|null $params */ public function get(?array $params, string $traceId): array { $id = is_array($params) ? (string) ($params['id'] ?? '') : ''; if ($id === '') { throw new BusinessException(new AgentError( code: 1001, message: 'Order not found', reason: 'ORDER_NOT_FOUND', domain: 'shop.example', param: 'id', hint: 'Pass an id that exists.', )); } return ['id' => $id]; } }
reason is the stable token an agent branches on. retryable defaults to false, so the same call is not repeated. Implement AgentFailure on an existing exception type when BusinessException does not fit. The wire shape is in docs/protocol-text-rpc.md.
bootstrap.php, relative to the working directory. An associative array arrives as an associative array. A JSON array arrives as a list. Both an empty object and an empty array arrive as [].
<?php declare(strict_types=1); use App\AppWorker; use App\OrderApi; $api = new OrderApi(); return static function (AppWorker $worker) use ($api): void { $worker->on('Order.get', $api->get(...)); };
config/server.php:
<?php declare(strict_types=1); use App\AppWorker; return [ 'workers' => [ 'App' => [ 'listen' => '127.0.0.1:9000', 'worker_class' => AppWorker::class, 'bootstrap' => 'bootstrap.php', 'child_count' => 4, ], ], ];
The business project autoloads App\ itself. This package only autoloads PhpServer\.
php vendor/bin/serverd start --foreground -c config/server.php
Call it from another PHP process. One connection, one call at a time. A list becomes a JSON array. An associative array becomes a JSON object.
<?php declare(strict_types=1); use PhpServer\Client\Client; use PhpServer\Client\RpcError; $client = new Client(); $client->connect('127.0.0.1:9000', 2.0); try { $order = $client->call('Order.get', ['id' => '7'], 'order-7')->result; } catch (RpcError $error) { $data = is_array($error->data) ? $error->data : []; if (($data['retryable'] ?? false) === true) { // Repeat this same call. Otherwise change $data['param'] using $data['reason']. } } $client->close();
The same call from the shell:
php vendor/bin/phpserver-rpc 127.0.0.1:9000 Order.get '{"id":"7"}' --trace-id=order-7
Send a frame
The spec is docs/protocol-text-rpc.md. With a server already listening, len is the body size in bytes and does not include the line ending:
body='{"method":"Echo.say","params":["hi"]}' printf 'TRPC/1 REQ 1 json %d\n%s\n' "$(printf %s "$body" | wc -c)" "$body" | nc 127.0.0.1 9000
Or the CLI:
bin/phpserver-rpc 127.0.0.1:9000 Echo.say '["hi"]' -v
-v prints frames on stderr, truncates the body to 256 bytes, and prints the trace-id. --raw prints the response body unchanged. Exit codes: 0 success, 1 RPC error, 2 protocol error, 3 network error, 64 usage error.
Single process
The contract is docs/worker-contract.md. Copy-paste sessions are in docs/debugging.md.
Echo, body hello:
php bin/worker --config config/server.echo.php Echo curl -sS http://127.0.0.1:9000/
Rpc example. Echo.say is registered by examples/Rpc/bootstrap.php. Stop the Echo process first; it also binds port 9000.
php bin/worker --config config/server.example.php Rpc
bin/phpserver-rpc 127.0.0.1:9000 Echo.say '["hi"]' -v
bin/worker logs to stdout. -v lowers the level to debug. --config (or -c) is followed by a worker name. Exit codes: 0 stopped by a signal, 1 config or runtime error, 64 usage error.
Prefork
Signal order and terminationGracePeriodSeconds are in docs/operations.md.
php bin/serverd start --foreground -c config/server.example.php
pid_file defaults to empty, so no PID file is written. stop, restart, and reload need one. status does not: it GETs the admin /status endpoint.
Docker
The dev image runs tests, static analysis, and the coding-style check. The runtime image runs bin/serverd start --foreground as uid 10001. Echo listens on 0.0.0.0:9000, admin on 0.0.0.0:9100. docker stop sends SIGTERM; the log contains master draining.
docker build --target dev -t phpserver:dev . docker run --rm phpserver:dev docker build --target runtime -t phpserver:runtime . docker run --rm -p 9000:9000 -p 9100:9100 phpserver:runtime
In another terminal: curl -sS http://127.0.0.1:9000/.
The base image php:8.4-cli-alpine is multi-arch, and this Dockerfile has no architecture-specific steps. Daily CI builds the native architecture only. Both platforms:
docker buildx build --platform linux/amd64,linux/arm64 --target runtime -t phpserver:runtime .
docker compose run --rm dev runs the same three checks and mounts the working tree (vendor stays the image copy). A shell: docker compose run --rm dev sh.
Kubernetes
Example manifests, not a Helm chart: deploy/k8s/. Liveness is admin /healthz, readiness is /readyz, terminationGracePeriodSeconds is 10, and the Service publishes port 9000 only. The notes in that directory are in Chinese.
Documentation
| Document | What it covers |
|---|---|
docs/protocol-text-rpc.md |
Wire spec for text-rpc/1 |
docs/configuration.md |
Config keys and PHPSERVER_* |
docs/worker-contract.md |
dealInput / dealProcess |
docs/operations.md |
Signals, drain, probes |
docs/debugging.md |
Short copy-paste sessions |
docs/scaffolding.md |
One-command project scaffold and Docker design |
docs/event-loop.md |
SelectLoop |
docs/ROADMAP.md |
v1 blueprint |
TODO.md |
Milestone checklist |
benchmarks/ |
How to record a benchmark |
CHANGELOG.md |
Library column and protocol column |
Example configs:
config/server.echo.php— smallest Echoconfig/server.example.php— every key
A bad config throws PhpServer\Exception\ConfigException. ConfigLoader::loadOrExit() writes the message to stderr and exits 1.
Development
composer install
composer test
composer analyse
composer cs
composer validate --strict
composer show --tree
composer show --no-dev --name-only stays empty. Fix style with composer cs:fix.
SelectLoop uses stream_select. When nothing is registered it sleeps, and it does not park a placeholder file descriptor. See docs/event-loop.md.
Provenance
This repository is an independent, clean-room rewrite inspired by the architecture of the original PHPServer (v1.3.4, from the PHP 5.6 era). That server was a multi-process PHP RPC server developed and used in production at Jumei (聚美优品). None of its source, configuration, or documentation is included here. What is kept is the original idea: a slight master that preforks workers, a select-based event loop, and a two-hook worker contract (dealInput / dealProcess). The names "PHPServer" and "Jumei" describe provenance only; this project is not affiliated with or endorsed by Jumei. See NOTICE.
Contributing
Open an issue or a pull request. Before sending code, run composer test, composer analyse, and composer cs on PHP 8.3 or newer. Keep composer.json require free of packages. Behavior that changes a config key, an error code, the signal order, or an admin path needs the matching line in docs/ updated in the same change.