Core Concepts

Data Transfer Objects

Using DTOs to write great objects in your Kipchak API

A Data Transfer Object (DTO) is the contract for one shape of data. The same class describes a response and, without the fields the server sets, a request body. Its attributes become a schema in the OpenAPI document.

Controllers read a request and return a response, models hold the logic, and DTOs carry the data between them. Generate one with kipchak make:dto, or with kipchak make:resource along with its model, controller, routes and tests.

A DTO

A DTO is a final readonly class with constructor properties in api/DataTransferObjects/, versioned like the controllers:

namespace Api\DataTransferObjects\v1;

use Kipchak\Core\Components\Dto\Check;
use Kipchak\Core\Components\Dto\Field;
use OpenApi\Attributes as OA;

#[OA\Schema(schema: 'Book', description: 'A book.', required: ['title', 'author'])]
final readonly class Book
{
    public function __construct(
        #[OA\Property(description: 'Identifier of the book.', readOnly: true, example: 1)]
        public int $id,

        #[Field(description: 'The title of the book.', maxLength: 200, minLength: 1, example: 'Middlemarch')]
        public string $title,

        #[Field(description: 'The author of the book.', maxLength: 100, minLength: 1, example: 'George Eliot')]
        public string $author,

        #[Field(description: 'The year of the book, from 1450 to the current year.', minimum: 1450, nullable: true, example: 1871)]
        #[Check([self::class, 'notInTheFuture'])]
        public ?int $year = null,
    ) {}

    public static function notInTheFuture(int $year): ?string
    {
        return $year > (int) date('Y') ? 'Must not be in the future.' : null;
    }
}

Rules are written once

Field (from core 3.19) takes everything OA\Property takes. Its minLength, maxLength, minimum, maximum, pattern and enum describe the property in the OpenAPI document, and the same values are enforced on a request body. There is no second statement of the rule to keep in step.

minLength and maxLength count characters, not bytes. A pattern is written as OpenAPI writes one, with no delimiters.

Check is for a rule an attribute argument cannot state, such as one that depends on the date. It names a static method that takes the value and returns what is wrong with it, or null. The OpenAPI document cannot state such a rule, so say what it does in the property's description.

Reading a request body

Input::from() reads the request's JSON body into a DTO. Give it any values the server sets, which replace whatever the client sent:

use Api\DataTransferObjects\v1\Book;
use Kipchak\Core\Components\Dto\Input;

public function create(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
    $book = (new BooksModel())->create(Input::from($request, Book::class, ['id' => 0]));

    return Http\Response::json($response->withHeader('Location', "/v1/books/{$book->id}"), $book, 201);
}

What an invalid body gets

Every field with a problem is reported at once, type errors and rules together. The Error middleware answers with a 400. From 1.36 it adds meta.errors, by field, beside the same message in data. For the body {"title":"","year":1449}:

{
    "code": 400,
    "status": "BAD_REQUEST",
    "meta": {
        "errors": {
            "title": ["Must be at least 1 character."],
            "author": ["This field is required."],
            "year": ["Must be at least 1450."]
        }
    },
    "data": "The book is not valid: title: Must be at least 1 character. author: This field is required. year: Must be at least 1450."
}

A nested property or a list item is named by its path, such as notes.1.text. One problem is reported for each field. A body that is not JSON answers The body is not valid JSON., with no meta.

Stored rows are not checked against the rules

The rules apply only through Input. A model that maps a database row into the DTO with a plain Valinor mapper checks its types and ignores Field and Check:

$book = (new MapperBuilder())->mapper()->map(Book::class, Source::array($row));

So tightening a rule never makes an existing row unreadable: an old record that breaks a new rule is still served, and only a new request carrying the same values is refused.

Existing DTOs

Nothing changes for a DTO that does not use Field. OA\Property(maxLength: 5) remains documentation only, and is not enforced. Change a property to Field when you want its rules enforced, one property at a time. The upgrade guide has the steps.

Previous
Middleware