PHPackages                             andrewdyer/php-actions - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. andrewdyer/php-actions

ActiveLibrary[API Development](/categories/api)

andrewdyer/php-actions
======================

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

02[5 issues](https://github.com/andrewdyer/php-actions/issues)PHPCI passing

Since Mar 12Pushed 3w agoCompare

[ Source](https://github.com/andrewdyer/php-actions)[ Packagist](https://packagist.org/packages/andrewdyer/php-actions)[ RSS](/packages/andrewdyer-php-actions/feed)WikiDiscussions main Synced 3mo ago

READMEChangelog (10)DependenciesVersions (2)Used By (0)

Actions
=======

[](#actions)

A framework-agnostic PHP library for building structured and predictable JSON API endpoints with standardised request and response handling.

[![Latest Stable Version](https://camo.githubusercontent.com/192bec387fe7a41c6b7641ee5f21c2864361503d530294d371183f8a07a5d52c/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f616374696f6e732f763f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/actions)[![Total Downloads](https://camo.githubusercontent.com/5747378c1f6e9da56aafbd68095053a043cea62fd90c7193f8cf735fb4cc9d41/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f616374696f6e732f646f776e6c6f6164733f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/actions)[![License](https://camo.githubusercontent.com/a71a8c254e507add2fcb78f1500c8d6cbeabee5397b34ef6ca8984bfb2db1ee1/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f616374696f6e732f6c6963656e73653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/actions)[![PHP Version Require](https://camo.githubusercontent.com/6a8a83a778fac2352eb3bf911ea301b75ea6a001f7e5ec278971ccf2e9691423/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f616374696f6e732f726571756972652f7068703f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/actions)

Introduction
------------

[](#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.

Prerequisites
-------------

[](#prerequisites)

- **[PHP](https://www.php.net/)**: Version 8.3 or higher is required.
- **[Composer](https://getcomposer.org/)**: Dependency management tool for PHP.

Installation
------------

[](#installation)

```
composer require andrewdyer/actions
```

Getting Started
---------------

[](#getting-started)

The examples below demonstrate how this library can be used with [Slim Framework 4](https://www.slimframework.com/).

> ⚠️ 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

[](#1-create-an-action)

The action validates the request, retrieves data, and returns a JSON response.

```
declare(strict_types=1);

namespace App\Http\Actions;

use AndrewDyer\Actions\AbstractAction;
use Psr\Http\Message\ResponseInterface;

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

        if (!ctype_digit($id)) {
            return $this->badRequest('User ID must be numeric.');
        }

        if ((int) $id !== 123) {
            return $this->notFound("User {$id} not found.");
        }

        return $this->ok([
            'id' => (int) $id,
            'name' => 'John Smith',
            'email' => 'john.smith@example.com',
        ]);
    }
}
```

### 2. Register the route

[](#2-register-the-route)

The action is wired into the Slim bootstrap so requests to `/users/{id}` are dispatched to the action class.

```
declare(strict_types=1);

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

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

$app = AppFactory::create();

// If using a container, ensure GetUserAction is resolvable there.
$app->get('/users/{id}', GetUserAction::class);

$app->run();
```

Usage
-----

[](#usage)

Once the route is registered, Slim invokes the action and returns the payload as JSON.

### Successful request

[](#successful-request)

```
GET /users/123
Accept: application/json

```

**Response: 200 OK**

```
{
  "data": {
    "id": 123,
    "name": "John Smith",
    "email": "john.smith@example.com"
  }
}
```

### Validation error

[](#validation-error)

```
GET /users/abc
Accept: application/json

```

**Response: 400 Bad Request**

```
{
  "error": {
    "type": "BAD_REQUEST",
    "description": "User ID must be numeric."
  }
}
```

### Resource not found

[](#resource-not-found)

```
GET /users/999
Accept: application/json

```

**Response: 404 Not Found**

```
{
  "error": {
    "type": "RESOURCE_NOT_FOUND",
    "description": "User 999 not found."
  }
}
```

Response helpers
----------------

[](#response-helpers)

Helper methods provided by `AbstractAction` generate structured JSON responses. Each builds the appropriate `ActionPayload` and writes it to the response.

MethodWhen to useStatusError type`ok(mixed $data, mixed $meta = null, int $statusCode = 200)`Successful operation with data payload200 (or custom)—`badRequest(?string $description = null)`Request is malformed or violates business rules400`BAD_REQUEST``unauthorized(?string $description = null)`Request lacks valid authentication credentials401`UNAUTHENTICATED``forbidden(?string $description = null)`Authenticated caller lacks required permissions403`INSUFFICIENT_PRIVILEGES``notFound(?string $description = null)`Requested resource does not exist404`RESOURCE_NOT_FOUND``notAllowed(?string $description = null)`HTTP method not allowed for the resource405`NOT_ALLOWED``serverError(?string $description = null)`Unexpected server error occurred500`SERVER_ERROR``notImplemented(?string $description = null)`Requested functionality has not been implemented501`NOT_IMPLEMENTED`> **Note:** When the `description` parameter is `null`, the `description` field is omitted entirely from the error response. API consumers should treat `description` as an optional field.

For full control over the payload, call `json(ActionPayloadInterface $payload)` directly.

Request helpers
---------------

[](#request-helpers)

Helper methods are available for accessing request data in a consistent and predictable manner.

### Route arguments

[](#route-arguments)

Route arguments are extracted from the URL pattern matched by your router (e.g., `/users/{id}`).

- **`getArgs(): array`** — Returns all route arguments as an associative array
- **`resolveArg(string $name): string|int`** — Retrieves a route argument by name. Throws a RuntimeException if the argument is missing.

#### Example: Fetching a resource by ID

[](#example-fetching-a-resource-by-id)

```
declare(strict_types=1);

namespace App\Http\Actions;

use AndrewDyer\Actions\AbstractAction;
use Psr\Http\Message\ResponseInterface;

final class GetOrderAction extends AbstractAction
{
    protected function handle(): ResponseInterface
    {
        // Extract the order ID from the route
        $orderId = (int) $this->resolveArg('id');

        // Your domain logic here...
        $order = $this->fetchOrder($orderId);

        return $this->ok($order);
    }
}
```

**Request:**

```
GET /orders/12345
Accept: application/json

```

### Request body

[](#request-body)

The request body can be accessed as an associative array using `getParsedBody()`.

- **`getParsedBody(): array`** — Returns the parsed request body as an array. Returns an empty array if no body is present. Throws a RuntimeException if the body cannot be parsed as an array.
- **`resolveBodyParam(string $name, mixed $default = null): mixed`** — Retrieves a body parameter by name. If a default value is provided, the parameter is optional and the default is returned when missing. If no default value is provided, the parameter is required and a RuntimeException is thrown when missing.

#### Example: Creating a resource

[](#example-creating-a-resource)

```
declare(strict_types=1);

namespace App\Http\Actions;

use AndrewDyer\Actions\AbstractAction;
use Psr\Http\Message\ResponseInterface;

final class CreateProductAction extends AbstractAction
{
    protected function handle(): ResponseInterface
    {
        // Required parameters (throw exception if missing)
        $name = $this->resolveBodyParam('name');
        $price = $this->resolveBodyParam('price');

        // Optional parameter with default
        $description = $this->resolveBodyParam('description', 'No description provided');

        // Your domain logic here...
        $product = $this->createProduct($name, (float) $price, $description);

        return $this->ok($product, null, 201);
    }
}
```

**Request:**

```
POST /products
Accept: application/json
Content-Type: application/json

{
  "name": "Wireless Mouse",
  "price": 29.99
}

```

**Response: 201 Created**

```
{
  "data": {
    "id": 456,
    "name": "Wireless Mouse",
    "description": "No description provided",
    "price": 29.99
  }
}
```

### Query parameters

[](#query-parameters)

Query parameters from the request URI can be accessed using two methods:

- **`getQueryParams(): array`** — Returns all query parameters as an associative array
- **`resolveQueryParam(string $name, mixed $default = null): mixed`** — Retrieves a query parameter by name. If a default value is provided, the parameter is optional and the default is returned when missing. If no default value is provided, the parameter is required and a RuntimeException is thrown when missing.

#### Example: Pagination and filtering

[](#example-pagination-and-filtering)

```
declare(strict_types=1);

namespace App\Http\Actions;

use AndrewDyer\Actions\AbstractAction;
use Psr\Http\Message\ResponseInterface;

final class ListProductsAction extends AbstractAction
{
    protected function handle(): ResponseInterface
    {
        // Required parameter (throws exception if missing)
        $category = $this->resolveQueryParam('category');

        // Optional parameters with defaults
        $page = max(1, (int) $this->resolveQueryParam('page', 1));
        $limit = max(1, (int) $this->resolveQueryParam('limit', 20));

        // Your domain logic here...
        $products = $this->fetchProducts($category, $page, $limit);
        $total = $this->countProducts($category);

        return $this->ok(
            $products,
            [
                'total' => $total,
                'page' => $page,
                'perPage' => $limit,
                'totalPages' => (int) ceil($total / $limit),
            ]
        );
    }
}
```

**Request**

```
GET /products?category=electronics&page=2&limit=10
Accept: application/json

```

**Response: 200 OK**

```
{
  "data": [...],
  "meta": {
    "total": 156,
    "page": 2,
    "perPage": 10,
    "totalPages": 16
  }
}
```

#### Example: Array query parameters

[](#example-array-query-parameters)

Query parameters may also contain array values (for example, `?tags[]=foo&tags[]=bar&tags[]=baz`):

```
protected function handle(): ResponseInterface
{
    // Resolves to ['foo', 'bar', 'baz']
    $tags = $this->resolveQueryParam('tags');

    // Your domain logic here...
    $items = $this->findByTags($tags);

    return $this->ok(['items' => $items]);
}
```

Exception handling
------------------

[](#exception-handling)

Domain exceptions are caught automatically by `AbstractAction` and mapped to appropriate HTTP responses. This is useful when exceptions are thrown from services, repositories, or other domain logic that should not be coupled to HTTP concerns. Extend the base exception classes to create domain-specific exceptions.

Base exceptionWhen to useStatusError type`BadRequestException`Request is malformed or violates business rules400`BAD_REQUEST``UnauthenticatedException`Request lacks valid authentication credentials401`UNAUTHENTICATED``ForbiddenException`Authenticated caller lacks required permissions403`INSUFFICIENT_PRIVILEGES``NotFoundException`Requested resource does not exist404`RESOURCE_NOT_FOUND``NotImplementedException`Requested functionality has not been implemented501`NOT_IMPLEMENTED`> **Note:** When an exception has an empty message, the `description` field is omitted from the error response. API consumers should treat `description` as an optional field.

Example:

```
declare(strict_types=1);

namespace App\Domain\Exceptions;

use AndrewDyer\Actions\Exceptions\NotFoundException;

final class UserNotFoundException extends NotFoundException
{
    public function __construct(int $id)
    {
        parent::__construct("User {$id} not found.");
    }
}
```

License
-------

[](#license)

Licensed under the [MIT license](https://opensource.org/licenses/MIT) and is free for private or commercial projects.

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance62

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity14

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/666597ea6e46748a89fe8764d1a45b4d0da97daf1bb1e9770ea34ae41f706d08?d=identicon)[andrewdyer](/maintainers/andrewdyer)

---

Top Contributors

[![andrewdyer](https://avatars.githubusercontent.com/u/8114523?v=4)](https://github.com/andrewdyer "andrewdyer (36 commits)")

---

Tags

actionsapiframework-agnosticjson-apiphppsr-7

### Embed Badge

![Health badge](/badges/andrewdyer-php-actions/health.svg)

```
[![Health](https://phpackages.com/badges/andrewdyer-php-actions/health.svg)](https://phpackages.com/packages/andrewdyer-php-actions)
```

###  Alternatives

[exsyst/swagger

A php library to manipulate Swagger specifications

35816.3M7](/packages/exsyst-swagger)[hubspot/api-client

Hubspot API client

24015.5M18](/packages/hubspot-api-client)[pocketmine/bedrock-protocol

An implementation of the Minecraft: Bedrock Edition protocol in PHP

172437.8k11](/packages/pocketmine-bedrock-protocol)[botman/driver-telegram

Telegram driver for BotMan

93452.6k6](/packages/botman-driver-telegram)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
