Creating your own Actions

Home » Documentation » Creating your own Actions

“Extensibility is the key to building future-proof systems. It’s not about predicting the future, but about creating architectures that thrive in the face of change.”

Robert C. Martin

Overview

Creating your own actions need 2 steps. (1) is about creating your action’s class. The other is injecting that action in Socket Conveyor’s workflow.

Action’s Class

You can create your own actions by extending any action, or by extending the action abstraction Conveyor\Actions\Abstractions\AbstractAction.

To get up to speed with this, let’s look at the BaseAction’s code:

<?php

namespace Conveyor\Actions;

use Conveyor\Actions\Abstractions\AbstractAction;
use InvalidArgumentException;

class BaseAction extends AbstractAction
{
    public const NAME = 'base-action';

    protected string $name = self::NAME;

    public function validateData(array $data): void
    {
        if (!isset($data['data'])) {
            throw new InvalidArgumentException('BaseAction required \'data\' field to be created!');
}
    }

    public function execute(array $data): mixed
    {
        $this->send($data['data'], $this->fd);
        return null;
    }
}

In this, you can see the 2 abstract functions implementations: validateData and execute.

Almost any logic can be implemented by looking at the AbstractAction code and customizing it as well.

Adding an Action to Socket Conveyor

You can add extra actions to Socket Conveyor in 2 different ways: (1) at the Conveyor class, (2) at the Conveyor Server.

1. Conveyor:

During the declaration of Socket Conveyor’s code, you can add your own actions like follows:

<?php

use Conveyor\Conveyor;
use OpenSwoole\WebSocket\Frame;
use OpenSwoole\WebSocket\Server;
use MyNamespace\MyCustomAction;

$websocket = new Server('0.0.0.0', 8080);

$websocket->on('message', function (Server $server, Frame $frame) use ($persistenceService) {
    Conveyor::init()
        ->server($server)
        ->fd($frame->fd)
        ->addActions([
            new MyCustomAction,
        ])
        ->closeConnections()
        ->run($frame->data);
});

$websocket->start();

2. Conveyor Server:

During the declaration of Conveyor Server, you can add your actions as a “conveyorOptions” parameter:

<?php

use Conveyor\ConveyorServer;
use Conveyor\ConveyorWorker;
use Conveyor\Actions\Interfaces\ActionInterface;

/** @var array<array-key, ActionInterface> $actions */
$actions = [new MyCustomAction];

ConveyorServer::start(
    conveyorOptions: [
        ConveyorWorker::ACTIONS => $actions,
    ],
);