Server Event Callback Style

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Introduction

When running a Swoole server, if you enable event_object and set it to true, Swoole will pass objects to your event callback functions instead of individual arguments.

To understand this change better, let's take a look at some examples but for more information, see the server configuration for event_object.

Server Event Object

For the following events, they will be passed a Swoole\Server\Event object:

  • Connect
  • Receive
  • Close
<?php
$server->on('Connect', function(Swoole\Server $server, Swoole\Server\Event $event)
{
    var_dump($event);
});

Swoole Server Packet

For the server Packet event, it will receive a Swoole\Server\Packet object:

<?php
$server->on('Packet', function (Swoole\Server $server, Swoole\Server\Packet $Packet)
{
    var_dump($Packet);
});

Swoole Server Pipe Message

For the server PipeMessage event, it will receive a Swoole\Server\PipeMessage object:

<?php
$server->on('PipeMessage', function(Swoole\Server $server, Swoole\Server\PipeMessage $msg)
{
    var_dump($msg);

    $object = $msg->data;

    $server->sendto($object->address, $object->port, $object->data, $object->server_socket);
});

Swoole Server Status Information

For the WorkerError event, it will receive a Swoole\Server\StatusInfo object:

<?php
$server->on('WorkerError', function(Swoole\Server $server, Swoole\Server\StatusInfo $info)
{
    var_dump($info);
});

Swoole Server Task

For the Task event, it will receive a Swoole\Server\Task object:

<?php
$server->on('Task', function(Swoole\Server $server, Swoole\Server\Task $task)
{
    var_dump($task);
});

Swoole Server TaskResult

For the task Finish event, it will receive a Swoole\Server\TaskResult object:

<?php
$server->on('Finish', function(Swoole\Server $server, Swoole\Server\TaskResult $result)
{
    var_dump($result);
});
Last updated on August 31, 2022