andrewdyer/php-actions

Framework-agnostic action utilities for building structured and predictable JSON API endpoints

Maintainers

Package info

github.com/andrewdyer/php-actions

pkg:composer/andrewdyer/php-actions

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-03-12 14:52 UTC

This package is auto-updated.

Last update: 2026-03-12 15:50:22 UTC


README

Framework-agnostic action utilities for building structured and predictable JSON API endpoints.

✨ Introduction

This library adheres to standard HTTP messaging principles (PSR-compliant) and provides a small set of utilities to standardise how actions handle requests and generate responses. By establishing clear patterns for success responses and error payloads, it helps keep action classes focused on domain logic while giving clients predictable, well-structured JSON responses, regardless of the framework or HTTP layer used.

📥 Installation

composer require andrewdyer/php-actions

🚀 Getting Started

The examples below demonstrate how this library can be used with Slim Framework 4.

⚠️ Slim and a PSR-7 implementation are not included as dependencies of this package and must be installed separately before running these examples.

1. Create an action

The action below reads a route argument and returns either a success or error JSON payload.

declare(strict_types=1);

namespace App\Http\Actions;

use Anddye\Actions\AbstractAction;
use Anddye\Actions\Payloads\ActionError;
use Anddye\Actions\Payloads\ActionPayload;
use Psr\Http\Message\ResponseInterface;

final class PingAction extends AbstractAction
{
    protected function handle(): ResponseInterface
    {
        $mode = (string) $this->resolveArg('mode');

        if ($mode !== 'ok') {
            return $this->respondWithJson(
                ActionPayload::error(
                    ActionError::badRequest('Mode must be "ok".'),
                    400
                )
            );
        }

        return $this->respondWithJson(
            ActionPayload::success([
                'message' => 'pong',
            ])
        );
    }
}

2. Register the route

The action is wired into the Slim bootstrap so requests to /ping/{mode} are dispatched to the action class.

declare(strict_types=1);

use App\Http\Actions\PingAction;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// If you're using a container, ensure PingAction is resolvable there.
$app->get('/ping/{mode}', PingAction::class);

$app->run();

📚 Usage

Once the route is registered, Slim will invoke your action and return the payload as JSON.

GET /ping/ok
Accept: application/json

200 OK

{
  "data": {
    "message": "pong"
  }
}
GET /ping/nope
Accept: application/json

400 Bad Request

{
  "error": {
    "type": "BAD_REQUEST",
    "description": "Mode must be \"ok\"."
  }
}