Search by

crazy-goat / workerman-bundle

crazy-goat

Symfony bundle providing a Workerman runtime for high-performance long-running HTTP servers, with built-in task scheduler, process supervisor, PHAR packaging, and event-loop integration.

Package info

github.com/crazy-goat/workerman-bundle

Type:symfony-bundle

pkg:composer/crazy-goat/workerman-bundle

Statistics

Installs: 99

Dependents: 0

Suggesters: 0

Stars: 2

Open Issues: 107

v0.31.0 2026-10-06 09:44 UTC

This package is auto-updated.

Last update: 2026-10-09 08:47:54 UTC


README

PHP ^8.2 Symfony ^6.4|^7.0|^8.0 Tests Status License

Workerman is a high-performance, asynchronous event-driven PHP framework written in pure PHP.
This bundle provides a Workerman integration in Symfony, allowing you to easily create an HTTP server, scheduler and supervisor all in one place. This bundle allows you to replace a traditional web application stack like php-fpm + nginx + cron + supervisord, all written in pure PHP (no Go, no external binaries). The request handler works in an event loop, which means the Symfony kernel and the dependency injection container are preserved between requests, making your application faster with fewer (or no) code changes.

Contributing

Please see CONTRIBUTING.md for information about branch protection rules and development workflow.

What's new in this fork

This section documents the differences between crazy-goat/workerman-bundle (this fork) and the upstream luzrain/workerman-bundle.

Dependencies & Compatibility

Aspect crazy-goat (this fork) luzrain (upstream)
PHP ^8.2 >=8.1
Symfony `^6.4 ^7.0
PSR-7 bridge Removed (not required) Required (psr/http-factory, psr/http-message, symfony/psr-http-message-bridge)

Features

  1. Middleware system — composable request/response pipeline with MiddlewareInterface, MiddlewareDispatchInterface, StaticFilesMiddleware (ETag, Last-Modified, 304 support, blocked extensions, dot-file blocking, symlink control, path traversal protection, LRU realpath cache with TTL, PHAR-aware path resolution), SymfonyController (kernel boot, request conversion, response, termination, service resetter), and a pipeline that is built once and cached. Each request uses one dispatcher object and one controller closure.

  2. Console commands — full server lifecycle management via ServerManager: workerman:server start/stop/restart/reload/status/connections, plus workerman:build:phar and workerman:build:bin for packaging.

  3. Slowloris / DoS protection — configurable connection_timeout for incomplete requests (default: 120s), keepalive_timeout for idle connections (default: 30s), and per-server body_size_cap.

  4. Response conversion with strategy pattern — BinaryFileResponseStrategy (uses Workerman's withFile(), supports SplTempFileObject, offset/maxlen, deleteFileAfterSend cleanup), StreamedResponseStrategy (chunked transfer encoding), DefaultResponseStrategy (large responses via chunked transfer directly to connection), header name normalization with caching. Upstream buffers everything in memory.

  5. Memory reload strategy — reloads the worker when emalloc'ed memory exceeds limit (default 128 MB); a gc_collect_cycles() is attempted once memory passes gc_limit (default 96 MB) — synchronously, before the reload decision, whenever the worker is also above limit (so a collection that frees enough memory avoids the reload), and deferred to the next event-loop tick otherwise; gc_cooldown (default 60s) limits collection frequency.

  6. Trusted hosts — trusted_hosts config key with regex patterns, rejects non-matching Host header via SuspiciousOperationException (400).

  7. Service state resetter integration — calls services_resetter after kernel termination to reset stateful services between requests (critical for long-running worker correctness).

  8. SSL validation — validates cert/key paths, rejects symlinks for security.

  9. Process inspection — /proc-based zombie detection, orphan killing, parent PID tracking.

  10. PHAR/BIN runtime support — runtime_dir config key with WORKERMAN_RUNTIME_DIR env var, PharHelper for runtime path resolution, automatic runtime directory creation, skips file monitor in PHAR mode, KernelFactory with PHAR-aware getCacheDir()/getLogDir().

  11. Custom exception hierarchy — 20 exception classes (plus 2 marker interfaces) under WorkermanExceptionInterface → WorkermanException → category bases (ServerException, KernelException, MiddlewareException, SchedulerException, ValidationException) with specific exceptions for the bundle's error cases. Upstream uses only generic PHP exceptions.

  12. Utils::reload() — programmatic worker reload from application code with reloadAllWorkers: true param.

  13. File upload validation — structural validation of uploaded files with clear error messages. Upstream has no validation.

  14. Extended Request class — adds the setHeader() method to Workerman's Request, required by the middleware system. withHeader() is a deprecated alias (since 0.23.0, removed in 1.0).

  15. ListenScheme enum — type-safe HTTP/HTTPS/WS/WSS scheme parsing. Upstream uses inline str_starts_with() checks.

  16. Trigger factory improvement — uses CronExpression::isValidExpression() for proper cron detection. Upstream uses a fragile heuristic (count(explode(' ', $expr)) === 5 && str_contains($expr, '*')).

  17. SchedulerWorker improvements — proper SIGCHLD handler that reaps children and logs exit codes/signals, file-lock-based PID management with symlink detection and inode mismatch protection. Upstream uses SIG_IGN for SIGCHLD and simple file_put_contents for PID.

  18. SupervisorWorker improvements — handler returns never type (process exits with code 1 on unexpected return), logs unexpected finish, skips processes with processes <= 0.

  19. Cache warmup improvements — signal-based success/failure detection (SIGKILL=success, SIGTERM=failure), configurable timeout via WORKERMAN_CACHE_WARMUP_TIMEOUT env var. Upstream uses simple pcntl_wait() with no timeout or error detection.

  20. Config loader improvements — ConfigSection enum, warmUp() validates all sections before writing, setBuildConfig() / getBuildConfig() for PHAR build config.

Code quality / DX

  • Full custom exception hierarchy (20 classes plus 2 marker interfaces) instead of generic \Exception
  • readonly classes where appropriate
  • Extracted ConfigurationTreeBuilder, ServicesConfigurator, WorkermanCompilerPass as separate testable classes (upstream uses anonymous closures/files)
  • ServerManager extracted as standalone service (testable)
  • ServiceMethod value object with validation (upstream uses raw strings)
  • ServiceHandlerTrait / ServiceErrorListenerTrait for shared logic
  • Extensive test suite (unit + integration + e2e)
  • PHPStan + Rector in CI pipeline

What was removed

  • PSR-7 pipeline: WorkermanHttpMessageFactory, psr/http-factory, psr/http-message, symfony/psr-http-message-bridge dependencies — replaced by direct Workerman→Symfony conversion.

Requirements

  • PHP 8.2 or newer.
  • ext-pcntl and ext-posix.
  • Symfony 6.4, 7 or 8.
  • Workerman 5.
  • Linux or macOS. Windows is not supported.

Optional: ext-event, ext-inotify, ext-zip and dragonmantank/cron-expression. See Getting started for what each one does.

Getting started

The short version is below. The full guide is docs/getting-started.md.

Install composer packages

composer require crazy-goat/workerman-bundle

Enable the bundle

<?php
// config/bundles.php

return [
    // ...
    \CrazyGoat\WorkermanBundle\WorkermanBundle::class => ['all' => true],
];

Configure the bundle

A minimal configuration might look like this. For all available options with documentation, see the command output.

$ bin/console config:dump-reference workerman
# config/services.yaml
services:
  workerman.middleware.static_files:
    class: CrazyGoat\WorkermanBundle\Middleware\StaticFilesMiddleware
    public: true
    arguments:
      $rootDirectory: '%kernel.project_dir%/public'

# config/packages/workerman.yaml
workerman:
  servers:
    - name: 'Symfony webserver'
      listen: http://127.0.0.1:8080
      processes: 4
      middlewares:
        - workerman.middleware.static_files

  reload_strategy:
    exception:
      active: true

when@dev:
  workerman:
    reload_strategy:
      file_monitor:
        active: true
        source_dir: ['%kernel.project_dir%/src']
        file_pattern: ['*.php', '*.yaml']
        # Polling fallback (used only without ext-inotify):
        polling_interval: 3
        max_files_per_tick: 500

Note: The example above binds an unprivileged port (8080) so it works without sudo. See Ports below 1024 for ports such as 80 or 443.

Note: processes is the number of workers of a server. If you leave it out, the default is the number of CPUs times 2. In a container the CPU limit is used, not the CPUs of the host. See docs/configuration.md.

Note: listen is required. If you leave it out, the server does not start and you get an Unsupported listen scheme error. Supported URI schemes: http://, https://, ws:// (WebSocket), wss:// (WebSocket over SSL). https:// and wss:// listeners additionally require local_cert and local_pk — see the TLS example.

Configuration reference

Every config key and every environment variable is in docs/configuration.md. To see the keys with their defaults, run bin/console config:dump-reference workerman.

Start application

Using the Symfony console command (the bin/console below refers to your application's Symfony console, not the bin/ directory shipped by this bundle):

$ bin/console workerman:server start
$ bin/console workerman:server start -d   # daemon mode

Note: All bin/console workerman:* commands throughout this document refer to your application's Symfony console, not the scripts in this bundle's bin/ directory. See bin/README.md for the bundle's own development scripts.

All commands and options are in docs/commands.md.

Config cache and runtime user

Since 0.25.0 the bundle refuses to load a configuration cache file that is not owned by the process that loads it. An owner mismatch stops workerman:server start with a RuntimeException. The most common case is a cache warmed up as root in a Docker build, with a server that runs as a non-root user.

Warm up the cache as the runtime user, or change the owner after the warm-up. The full guide, with the error message, is in Deployment, and a tested Dockerfile is in Docker. The threat model is in Config Cache File Protection. If you cannot change who warms the cache, see Guard downgrade.

Stop a server that was started by an older version before you upgrade to 0.25: see Upgrading to 0.25.

Manage the server

You can stop, restart, reload and inspect the server with bin/console workerman:server. See docs/commands.md for all actions, options, the connections output and Utils::reload().

Reload strategies

A worker keeps the Symfony kernel between requests, so it must be replaced sometimes. Reload strategies decide when: after an exception, after N requests, at a memory limit, after a file change or after each request. You can also write your own strategy. See docs/reload-strategies.md.

Middlewares

Middlewares run before the Symfony controller and after it. A middleware implements CrazyGoat\WorkermanBundle\Middleware\MiddlewareInterface and is listed under workerman.servers[].middlewares. The bundle has a StaticFilesMiddleware for static files. See docs/middlewares.md for the interface, the order of the layers and the static file headers. For the listen address, workers, timeouts and streamed responses, see docs/http-server.md.

Scheduler

Periodic tasks are configured with the #[AsTask] attribute or with the workerman.task tag. A schedule can be seconds, an ISO 8601 duration, a relative date, a date and time, or a cron expression. See docs/scheduler.md for the schedule formats, the fixed-rate rule, jitter, locks and errors.

Supervisor

Long-running processes are configured with the #[AsProcess] attribute or with the workerman.process tag. The bundle starts them again when they end. See docs/supervisor.md for the parameters, the restart rules and errors.

Packaging (experimental)

⚠️ Experimental: PHAR and standalone binary packaging are new features. The API may change in future releases.

The bundle provides commands to package your Symfony application as a standalone PHAR archive or a native binary:

# Build a PHAR archive
$ php -d phar.readonly=0 bin/console workerman:build:phar

# Build a standalone binary (requires phpmicro.sfx)
$ php -d phar.readonly=0 bin/console workerman:build:bin

# Options
$ php -d phar.readonly=0 bin/console workerman:build:phar --help
$ php -d phar.readonly=0 bin/console workerman:build:bin --help

See docs/build-packaging.md for full documentation, build configuration options, and known limitations.

For an overview of all documentation files, see docs/.

For security-related documentation including Host-header protection and trusted hosts configuration, see docs/security.md.

For long-running worker gotchas, state pollution, stale DB connections, blocking I/O, and other common issues, see docs/troubleshooting.md.

License

This bundle is open-sourced software licensed under the MIT license.