How PHP Swoole works

PHP Swoole is different from the traditional stateless PHP model, a Swoole application runs in CLI mode like how Node.js does but with a different design using coroutines that don't introduce callback hell.

Swoole enables you to keep your application running in memory, allowing you to run PHP servers in a stateful manner, reducing the latency of requests because any bootstrapping or application startup can be done before a server is ready to take requests.

You can either run Swoole directly on your network or use Apache or Nginx with a proxy pass through setup to accept requests. Swoole simplifies the PHP server setup as you don't need to run a separate HTTP server, it is all handled at the PHP level, replacing the need for PHP-FPM.

How PHP Swoole works

PHP Swoole internal

The differences between PHP Swoole with PHP-FPM the traditional PHP model are:

  • PHP Swoole supports TCP, UDP and UnixSocket
  • PHP Swoole uses Non-blocking I/O mode with epoll or kqueue
  • PHP Swoole forks several worker processes based on CPU core number to utilise all CPU cores.
  • PHP Swoole supports Long-live connections for WebSocket server or TCP/UDP server.
  • PHP Swoole supports more server-side protocols: TCP/UDP/HTTP/HTTP2/WebSocket
  • PHP Swoole preload PHP files into memory.
  • PHP Swoole can manage and reuse the status in memory with PHP Swoole Memory Management Modules.
  • Coroutine based concurrency compare with waterfall in PHP-FPM.

Swoole Server Structure

Master process

Master process is the first entry point for the Swoole Server.

Reactor threads in Master process

Reactor threads are created in the Master process to handle client side network connections and network I\O.

Manager process

Manager process create or destroy Worker processes and Task Worker processes.

Worker process

Worker process receive data from the Reactor threads and execute business logic, then send back the response to Reactor threads.

Your application code should be run within Worker processes.

Task Worker process

Task processes are used to offload code which will block the event-loop or coroutines that are running.

Task Worker processes receive data from Worker process and send back the result to the Worker process.

A Worker process sends data to a Task worker with the following functions:

  • Swoole\Server->task
  • Swoole\Server->taskCo
  • Swoole\Server->taskwait
  • Swoole\Server->taskWaitMulti

A Task worker process sends results back to Worker process with: Swoole\Server->finish.

Interested with PHP Swoole? Get Started with PHP Swoole now!