Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Workerman Bundle Laravel Package

crazy-goat/workerman-bundle

Symfony bundle integrating Workerman to run a high-performance async HTTP server, scheduler and supervisor in pure PHP. Keeps the Symfony kernel/container alive between requests for faster apps. Supports SO_REUSEPORT and optional direct Request creation for speed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require crazy-goat/workerman-bundle
    

    Enable in config/bundles.php:

    CrazyGoat\WorkermanBundle\WorkermanBundle::class => ['all' => true],
    
  2. Configure the Server Define a basic HTTP server in config/packages/workerman.yaml:

    workerman:
      servers:
        - name: 'Symfony HTTP Server'
          listen: 'http://0.0.0.0:8080'
          processes: 4
    
  3. Start the Server

    bin/console workerman:server start
    

    For daemon mode (detached):

    bin/console workerman:server start -d
    

First Use Case: Replace PHP-FPM

Replace php-fpm + nginx with a single Workerman process:

  • No external dependencies: Pure PHP, no Go/Node.js.
  • Event-loop integration: Symfony kernel persists between requests (faster than PHP-FPM).
  • Example: Serve a Symfony controller directly:
    // src/Controller/ApiController.php
    namespace App\Controller;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    
    class ApiController extends AbstractController {
        public function index(): Response {
            return new Response('Hello, Workerman!');
        }
    }
    
    Access via http://localhost:8080/api.

Implementation Patterns

Workflows

  1. Development Workflow

    • Use file_monitor reload strategy for hot-reloading:
      workerman:
        reload_strategy:
          file_monitor:
            active: true
      
    • Install php-inotify for efficient file monitoring:
      pecl install inotify
      
  2. Production Workflow

    • Daemonize: Run in detached mode (-d flag) with a reverse proxy (e.g., Nginx).
    • Privilege Dropping: Bind to port 80/443 as root, then drop privileges:
      workerman:
        user: www-data
        group: www-data
      
    • PHAR Packaging: Bundle the app into a single PHAR for deployment:
      bin/console workerman:phar create
      
  3. Task Scheduling

    • Schedule a cron job via attributes:
      use CrazyGoat\WorkermanBundle\Scheduler\Schedule;
      
      #[Schedule('*/5 * * * *')] // Every 5 minutes
      public function cleanupDatabase(): void {
          // Task logic
      }
      
    • Or via YAML:
      services:
        App\Command\CleanupCommand:
          tags: ['workerman.scheduler']
          arguments:
            $schedule: 'PT1H' # Every hour
      

Integration Tips

  • Static Files: Use StaticFilesMiddleware to serve assets:

    services:
      workerman.middleware.static_files:
        class: CrazyGoat\WorkermanBundle\Middleware\StaticFilesMiddleware
        arguments:
          $rootDirectory: '%kernel.project_dir%/public'
    

    Register in workerman.yaml under middlewares.

  • WebSockets: Add a WebSocket server:

    workerman:
      servers:
        - name: 'WebSocket Server'
          listen: 'ws://0.0.0.0:8081'
          processes: 2
    
  • GRPC Support: Enable fork support for grpc extension:

    export GRPC_ENABLE_FORK_SUPPORT=1
    bin/console workerman:server start
    

Gotchas and Tips

Pitfalls

  1. Port Binding

    • Issue: Binding to ports <1024 requires root or CAP_NET_BIND_SERVICE.
    • Fix: Use a reverse proxy (e.g., Nginx) to forward traffic to Workerman’s port (e.g., 8080).
  2. Memory Leaks

    • Issue: Unbounded memory growth can crash workers.
    • Fix: Enable memory reload strategy:
      workerman:
        reload_strategy:
          memory:
            active: true
            limit: 268435456 # 256 MB
      
  3. File Monitoring

    • Issue: Without php-inotify, polling mode is CPU-intensive.
    • Fix: Install php-inotify:
      pecl install inotify
      
  4. GRPC Deadlocks

    • Issue: GRPC extension deadlocks in forked processes.
    • Fix: Set GRPC_ENABLE_FORK_SUPPORT=1 before starting Workerman.
  5. Middleware Order

    • Issue: Middlewares execute in reverse order (last registered = first executed).
    • Fix: Register cross-cutting concerns (e.g., auth) last in the list.

Debugging

  • Check Connections:

    bin/console workerman:server connections
    

    Look for ESTABLISHED connections with high Recv-Q/Send-Q (potential hangs).

  • Logs:

    • Workerman logs to var/log/workerman.log.
    • Use stdout_file to capture echo/var_dump output:
      workerman:
        stdout_file: '%kernel.project_dir%/var/log/workerman.stdout.log'
      
  • Graceful Reloads:

    • Use -g flag for graceful stops/reloads to avoid connection drops:
      bin/console workerman:server reload -g
      

Extension Points

  1. Custom Reboot Strategies Implement RebootStrategyInterface for custom reload logic:

    use CrazyGoat\WorkermanBundle\Reboot\RebootStrategyInterface;
    use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
    
    #[AutoconfigureTag('workerman.reboot_strategy')]
    class CustomRebootStrategy implements RebootStrategyInterface {
        public function shouldReboot(): bool {
            return someCondition();
        }
    }
    
  2. Custom Middlewares Create middleware for request/response manipulation:

    use CrazyGoat\WorkermanBundle\Middleware\MiddlewareInterface;
    use CrazyGoat\WorkermanBundle\Http\Request;
    use Workerman\Protocols\Http\Response;
    
    class LoggingMiddleware implements MiddlewareInterface {
        public function __invoke(Request $request, callable $next): Response {
            // Pre-processing
            $response = $next($request);
            // Post-processing
            return $response;
        }
    }
    

    Register in services.yaml and workerman.yaml.

  3. Event Listeners Listen to Workerman events (e.g., WorkerStart, WorkerStop):

    use CrazyGoat\WorkermanBundle\Event\WorkerEvent;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(event: 'workerman.worker.start', method: 'onWorkerStart')]
    public function onWorkerStart(WorkerEvent $event): void {
        // Handle worker start
    }
    

Performance Tips

  • Reuse Ports: Enable reuse_port for kernel-level load balancing (Linux):
    workerman:
      servers:
        - name: 'HTTP Server'
          listen: 'http://0.0.0.0:8080'
          reuse_port: true
    
  • PHP-Event Extension: Install for better event-loop performance:
    pecl install php-event
    
  • Process Count: Start with processes: 4 and adjust based on CPU cores (e.g., 2 * CPU cores).

Configuration Quirks

  • Environment Variables: Override defaults via env vars:
    export WORKERMAN_RUNTIME_DIR=/custom/path
    export WORKERMAN_CACHE_WARMUP_TIMEOUT=60
    
  • PHAR Mode: In PHAR builds, runtime_dir defaults to the PHAR’s directory. Ensure writable paths:
    workerman:
      runtime_dir: '/tmp/workerman_runtime'
    
  • Trusted Hosts: Restrict allowed hosts to prevent HTTP Host header attacks:
    workerman:
      trusted_hosts: ['^example\.com$', '^localhost$']
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity