Moving to Kipchak
Moving to Kipchak from Slim
Move a Slim 4 JSON API to Kipchak, what carries over unchanged, and what your clients will notice
Who this page is for
You have a JSON API in Slim 4 and you are moving it to Kipchak. Kipchak is built on Slim 4, so most of your code carries over as it is: the routes, the PSR-7 requests and responses, PSR-15 middleware and Slim's HTTP exceptions. What Kipchak adds is the rest of an API around them: a project layout, drivers for databases and services, one JSON error format, validation from typed classes, an OpenAPI document, tests, and FrankenPHP in worker mode.
This page takes one small API, a bookshelf, as a Slim developer would write it, and moves it to Kipchak one part at a time. It starts with what you gain, and for each part says what carries over, what changes, and what your API's clients will notice.
Both versions are complete, and pass the same black-box test suite of 47 checks over HTTP and their own PHPUnit tests. The versions used:
| Version | |
|---|---|
| Slim | slim/slim 4.15.3, slim/psr7 1.8.0, doctrine/dbal 4.5, zircote/swagger-php 6, PHP 8.5 on PHP-FPM behind Caddy |
| Kipchak | starter 4.6 (core 3.19, Error middleware 1.36, Doctrine driver 1.55), PHP 8.5 on FrankenPHP in worker mode |
Every statement about Slim on this page links to the Slim 4 documentation and was checked against the running Slim version.
What Kipchak gives you
Slim gives you a router and a request pipeline, and leaves every other decision to you. Kipchak keeps Slim, and makes those decisions for you, in the way a JSON API needs. Each point below is shown from the Kipchak bookshelf.
Rules written once. The Slim bookshelf states each rule twice: in a hand-written problems() check, and again in an OA\Schema for the document. In Kipchak the rules live in the DTO's Field attributes, which are enforced on request bodies and written into the document. The Book schema the Kipchak bookshelf generates, from the DTO below:
"title": { "description": "The title of the book.", "type": "string", "example": "Middlemarch", "maxLength": 200, "minLength": 1 },
"year": { "description": "The year of the book, from 1450 to the current year.", "type": "integer", "example": 1871, "nullable": true, "minimum": 1450 }
Errors your clients can use. With Slim's error middleware set for production, the Slim bookshelf answers "400 Bad Request" in place of the controller's message, and an HTML page to a client that does not ask for JSON. Kipchak answers every error as JSON, with the message your code gave, and a 405 with the methods the route allows (see Errors).
A document served and checked. The starter serves /openapi.json, and the CLI checks it against the OpenAPI specification and against the routes: a route with no operation, an operation with no route or an undeclared path parameter is an error, and the command exits with 1, so it can gate a release in CI (openapi:validate):
$ vendor/bin/kipchak openapi:validate --strict
The document is valid. 0 errors, 0 warnings.
A whole resource, tested and documented, in one command. make:resource writes the DTO, model, controller, routes and tests. Run on the bookshelf, it added an Authors resource whose seven tests pass and whose operations are in the document:
$ vendor/bin/kipchak make:resource Authors --crud --fields='id:int,name:string,born:?int'
Created api/DataTransferObjects/v1/Author.php
Created api/Models/Authors.php
Created api/Controllers/v1/Authors.php
Created routes/v1/authors.php
Created tests/AuthorsTest.php
$ vendor/bin/phpunit
OK (32 tests, 80 assertions)
$ vendor/bin/kipchak openapi:validate --strict
The document is valid. 0 errors, 0 warnings.
Drivers and middleware, configured and in order. Databases, caches, queues and identity come as drivers and middleware, each with its configuration file. kipchak add installs one, copies its configuration and initialises it in the right place. Adding JWT validation against an identity provider's keys (auth-jwks, with issuer and audience checks) and rate limiting (Subashi, which answers 429) to the bookshelf:
$ vendor/bin/kipchak add auth-jwks
Created config/kipchak.auth.jwks.php
Modified middlewares/middlewares.php
$ vendor/bin/kipchak add subashi
Created config/kipchak.subashi.php
Modified drivers/drivers.php
Modified middlewares/middlewares.php
Worker mode from the start. Kipchak runs on FrankenPHP in worker mode: the API boots once and serves many requests, where PHP-FPM boots it for each one.
Your assistant knows the conventions. The starter includes an AGENTS.md that describes the project to coding assistants, and the Kipchak agent skill teaches them Kipchak's conventions.
The bookshelf
| Method and path | Success | Errors |
|---|---|---|
GET /v1/books | 200, the books ordered by ID; optional ?author= filter | 400 if author is empty |
GET /v1/books/{id} | 200, the book | 404 if no book has the ID, or the ID is not an integer |
POST /v1/books | 201, the book as created, with a Location header | an invalid body (see Validation) |
DELETE /v1/books/{id} | 204, no body | 404 if no book has the ID |
GET /openapi.json | 200, an OpenAPI 3 document generated from the code |
A book has id (set by the server), title (1 to 200 characters), author (1 to 100 characters) and year (optional; from 1450 to the current year). The data lives in SQLite.
Start the Kipchak project
composer create-project kipchak/starter bookshelf
cd bookshelf
vendor/bin/kipchak add doctrine
The starter comes with the Kipchak CLI. kipchak add doctrine installs the Doctrine driver, copies its configuration to config/kipchak.doctrine.php and initialises it in drivers/drivers.php.
A Slim app is whatever its author wires up in public/index.php. The Slim bookshelf builds its app in a factory:
// src/Application.php
$controller = new BooksController(new Books(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => $database])));
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(false, true, true);
$app->group('/v1', function (RouteCollectorProxy $group) use ($controller) {
// the four routes
});
In Kipchak, Api::boot() builds the Slim app and its container, and wires it up from the project's folders, always in this order:
| What | Slim bookshelf | Kipchak |
|---|---|---|
| The app | AppFactory::create() | Api::boot(), from html/index.php |
| Services | constructed in the factory | drivers, initialised in drivers/drivers.php, configured in config/ |
| Middleware | $app->add...() calls | middlewares/middlewares.php |
| Routes | in the factory | routes/, one file per resource and version |
| Body parsing | addBodyParsingMiddleware() | built in: Input::from() reads and validates the body |
| Errors | addErrorMiddleware() | the Error middleware, in middlewares/middlewares.php |
Any PSR-15 middleware you wrote for Slim works in Kipchak: add it in middlewares/middlewares.php (Middleware).
Routes
The routes carry over unchanged. The Kipchak bookshelf's routes/v1/books.php is the Slim bookshelf's group, with one difference:
$app->group('/v1', function (RouteCollectorProxy $group) {
$group->get('/books', [Controllers\v1\Books::class, 'list']);
$group->get('/books/{id:[0-9]+}', [Controllers\v1\Books::class, 'get']);
$group->post('/books', [Controllers\v1\Books::class, 'create']);
$group->delete('/books/{id:[0-9]+}', [Controllers\v1\Books::class, 'delete']);
});
The Slim bookshelf passes a controller it constructed ([$controller, 'list']). Kipchak names the class, and the container constructs it: a controller extends Controllers\Base, which gives it the container and the logger. The placeholders, {id:[0-9]+} and the rest of Slim's routing are the same. vendor/bin/kipchak routes lists every route.
The database
The Slim bookshelf opens a Doctrine DBAL connection in its factory. In Kipchak the connection is configured in config/kipchak.doctrine.php:
'dbal' => [
'enabled' => true,
'connections' => [
'primary' => [
'driver' => 'pdo_sqlite',
'path' => env('SQLITE_PATH', dirname(__DIR__) . '/var/books.sqlite'),
],
],
],
and the driver gives it to any class that asks:
$connection = Doctrine::get('dbal.primary');
So the Slim bookshelf's Books class, which queries with DBAL, moves to api/Models/Books.php with only its constructor changed. The Kipchak bookshelf goes one step further and uses the Doctrine ORM, which the same driver configures (see the Doctrine driver); you can keep DBAL.
The schema moves from database/schema.sql and a script that runs it, to a migration with a rollback after -- Down, which the driver runs and records:
-- migrations/database/20261108000000_create_books.sql
CREATE TABLE books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(200) NOT NULL,
author VARCHAR(100) NOT NULL,
year INTEGER NULL
);
-- Down
DROP TABLE books;
php vendor/bin/doctrine migrations:up --em=primary
The request and its validation
A Slim API chooses its own validation. The Slim bookshelf checks the parsed body by hand, and states the same rules a second time for the OpenAPI document:
#[OA\Schema(schema: 'Book', required: ['title', 'author'], properties: [
new OA\Property(property: 'id', type: 'integer', readOnly: true, example: 1),
new OA\Property(property: 'title', type: 'string', maxLength: 200, minLength: 1, example: 'Middlemarch'),
new OA\Property(property: 'author', type: 'string', maxLength: 100, minLength: 1, example: 'George Eliot'),
new OA\Property(property: 'year', type: 'integer', minimum: 1450, nullable: true, example: 1871),
])]
final class BookSchema
{
public static function problems(mixed $body): array
{
if (!is_array($body)) {
return ['body' => 'The body must be a JSON object.'];
}
$problems = [];
$title = $body['title'] ?? null;
if (!is_string($title) || mb_strlen($title) < 1 || mb_strlen($title) > 200) {
$problems['title'] = 'title is required and must be a string of 1 to 200 characters.';
}
// author and year in the same way
return $problems;
}
}
In Kipchak the DTO is a typed class, and each Field states a rule once: it is enforced on request bodies and appears in the OpenAPI document. A rule that is not a simple limit is a Check:
#[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;
}
}
The controller reads the body into it, giving id the value the server will replace:
$book = (new BooksModel())->create(Input::from($request, Book::class, ['id' => 0]));
Input::from() replaces both the body parsing middleware and the hand-written checks. A body that is not JSON, or that breaks any rule, is answered with every problem at once. Both bookshelves refuse "year": "1871": a string is not an integer in either.
Controllers and responses
Action signatures carry over: (ServerRequestInterface $request, ResponseInterface $response, array $args). The Slim bookshelf writes JSON with a helper of its own:
private static function json(Response $response, mixed $data, int $status = 200): Response
{
$response->getBody()->write(json_encode($data, JSON_THROW_ON_ERROR));
return $response->withHeader('Content-Type', 'application/json')->withStatus($status);
}
Kipchak's Http\Response::json() does the same, inside Kipchak's envelope:
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);
}
| Slim bookshelf | Kipchak bookshelf |
|---|---|
{"id": 1, "title": "Middlemarch", "author": "George Eliot", "year": 1871} | {"code": 200, "status": "OK", "data": {"id": 1, "title": "Middlemarch", "author": "George Eliot", "year": 1871}} |
[{"id": 1, ...}, ...] | {"code": 200, "status": "OK", "data": [{"id": 1, ...}, ...]} |
throw new HttpNotFoundException($request, ...) and the other HTTP exceptions carry over unchanged; what changes is how they are answered.
Errors
The Slim bookshelf uses Slim's error middleware, with error details off, as in production:
$app->addErrorMiddleware(false, true, true);
Slim chooses the format of an error from the request's Accept header (error handling and rendering), and with details off it answers with the status alone. The running Slim bookshelf:
| Request | Slim bookshelf |
|---|---|
GET /v1/books/99, Accept: application/json | 404, {"message": "404 Not Found"} |
GET /v1/books?author=, Accept: application/json | 400, {"message": "400 Bad Request"}: the controller's "author must not be empty." is not shown |
GET /v1/books/99, no Accept | 404, an HTML page |
Kipchak's Error middleware answers every error as JSON in the envelope, whatever the Accept header, and keeps the message the code gave:
{ "code": 404, "status": "RESOURCE_NOT_FOUND", "data": "No book has the ID 99." }
{ "code": 400, "status": "BAD_REQUEST", "data": "author must not be empty." }
A method the route does not allow is answered with the methods it does:
{ "code": 405, "status": "NOT_ALLOWED", "data": "Method not allowed. Must be one of: GET, DELETE" }
An invalid body, {"title": "", "year": 1449}, is 422 from the Slim bookshelf, with the shape its author chose:
{
"errors": {
"title": "title is required and must be a string of 1 to 200 characters.",
"author": "author is required and must be a string of 1 to 100 characters.",
"year": "year must be an integer from 1450 to 2026."
}
}
and 400 from Kipchak, with each field's problems in meta.errors:
{
"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."
}
The starter initialises the Error middleware twice, as the innermost and the outermost middleware, so that an exception from a route and one from any other middleware get the same answer. Keep your own middleware between the two.
The OpenAPI document
Both bookshelves use swagger-php attributes, so your operation attributes carry over. The Slim bookshelf generates the document in a route; the starter serves it at /openapi.json already, and adds the envelope to every response and the error envelope to every 4xx, so an operation declares only its data. With Field, the schema's rules come from the DTO and are stated once. vendor/bin/kipchak openapi:validate checks the document.
Tests
Both bookshelves test with PHPUnit, sending PSR-7 requests to the app with no web server. The Slim bookshelf builds a new app on a new temporary database for each test. The starter's ApiTestCase boots the API once per process, as a FrankenPHP worker does, so tests run against the same long-lived app as production; the Kipchak bookshelf's setUp() puts the three seed books back before each test.
Running it
The Slim bookshelf runs on PHP-FPM behind Caddy: each request starts with a fresh PHP state. Kipchak runs on FrankenPHP in worker mode: the API boots once and each worker serves many requests. The starter's Dockerfile and compose.yaml run it:
docker compose up --watch
This is the one change that can break code that moves unchanged. Under PHP-FPM, a static property or a service that remembers something from one request is thrown away at the end of it. In worker mode it is still there for the next request, and the next user. Before you move code that keeps state, read Caddy and FrankenPHP. If you need it, the starter also has a front controller and a Caddyfile for running without worker mode.
What your clients will notice
| Slim bookshelf | Kipchak bookshelf | |
|---|---|---|
| A success | the book, or an array of books | {"code": 200, "status": "OK", "data": ...} |
| An invalid body | 422, {"errors": {field: message}} | 400, {"code", "status", "meta": {"errors": {field: [messages]}}, "data"} |
| A body that is not JSON | 422, {"errors": {"body": ...}} | 400, "The body is not valid JSON." |
| An error's message | the status only ("404 Not Found"), with details off | the message the code gave |
An error without Accept: application/json | HTML | JSON |
| CORS headers | none | none until the origins are listed in CORS_ALLOWED_ORIGINS; the starter then answers preflight requests (CORS) |
Everything else is the same: the paths, the methods, the fields and their rules, 201 with Location, 204, and 404. If your clients cannot change when you move, tell them which of these shapes change, or bring the change in under a new version of the API (see Versioning).
Trade-offs
A Slim app has only the parts its author added; Kipchak's starter comes with a layout, a boot order and an envelope around every response, which are more to learn before the first route. Worker mode also asks you to keep request state out of statics, which PHP-FPM did for you. In return, the decisions every API needs are made, wired and tested.
Next steps
- Getting started and the starter project
- Data Transfer Objects: rules, checks and every problem reported at once
- Doctrine driver: DBAL connections, the ORM and migrations
- Middleware: the Kipchak middleware, and where your own goes
- Kipchak CLI:
make:resourcewrites a resource's DTO, model, controller, routes and tests in the starter's conventions