A Rest api application writen with CakePHP
All code is licensed under MIT License
- Read this entire document
- Check if files are auto-generated (don't edit them!)
- Use existing patterns (check similar components first)
- Refactor Over Hack: Before adding changes, evaluate whether a refactor is needed. Avoid quick hacks or case-specific fixes — prefer clean, well-structured solutions that are maintainable long-term. If existing code needs restructuring to accommodate a change properly, refactor first.
- Consistency: Match existing code style and patterns
- Readability: Avoid long inline expressions (ternaries, complex conditions) — extract them into named variables
- DRY: Extract duplicated logic into reusable domain functions rather than repeating inline expressions
- Maintainability: Clear naming. Follow SOLID and Clean Code (Robert C. Martin) principles.
- Do not write any comments at all: If you feel the need to write a comment explaining something, extract a variable or a function with a meaningful name, following SOLID and Clean Code (Robert C. Martin). A magic number becomes a named constant; a condition becomes a named predicate; a block becomes a named function. This includes JSDoc, section dividers (
// ─── Section ───), inline notes, and per-section UI comments. Compiler and tooling directives (eslint-disable,@ts-expect-error,#!/usr/bin/env) are not comments and are exempt. - Testing: Write tests for new features
We are using docker to develop run tests (where the code in local will be used in the server in real time), and make the system run in production. Each docker service works as if it were an independent machines running on the same local network.
All details from those machines are defined in the docker-compose file. Here a few important notes:
- Ports definition: host machine : container
- Links: indicates dependencies between services
- Volumes: files are linked, so they are updated in the host and the container in real time.
Run from docker-compose:
docker-compose -f ./docker-compose-dev.yml up -dRunning docker compose will start the http server (nginx) on port 80 and 443 by default (customizable from docker-compose-dev.yml file).
In order to use the ports 80 or 443 docker must have Admin rights.
Connect as root to the database launched using docker-compose (e.g. you can run exec on the container from nginx) and create a new default db for the project
(check config/app_local.php file for the credentials)
Connect to the nginx container using exec and run composer
cd /var/www/cplatform/public/app_rest/
composer installAfter running composer install, the application should be served in http://localhost as root json page.
In order to get the database populated, the ping-check endpoint (a link is available in the root json page) should be called
twice with ?seeds=true, as api/v1/ping/pong?seeds=true
(the first call creates the database and runs the migrations, the second populates it with the seeds)
Seeds only ever fill a table that is empty, so the parameter is safe to repeat, but it has to be asked for: without it the endpoint runs migrations only. That is deliberate — the endpoint is reachable in every environment, and nothing that writes data should happen by merely visiting a URL.
From the root json page, the events list endpoint is also referenced.
In similar way navigation within the endpoints should be possible using the _links property provided in each object
(using Firefox clicking on the links should work by default, in Chrome a json-viewer extension may be needed)
The local path is the location of this readme file, and it should be mapped to /var/www/cplatform/public
When running test use /var/www/cplatform/public/app_rest/phpunit.xml.dist as default configuration file.
Also add /var/www/cplatform/public/app_rest/vendor/autoload.php as a default autoload file
- Connect to the container using exec
- Navigate to the main path with
cd /var/www/cplatform/public/app_rest - Avoid running commands as root (since it can cause permission problems), change the user with:
su composeruser
The nginx service in docker-compose-dev.yml already has PHP installed, so tests are run inside it
(there is no need to have PHP installed locally). This is especially useful when working with an IDE that has no test integration, or with an AI CLI tool that cannot run tests through Docker on its own.
Always use the -T flag (it disables TTY allocation). Without it the command appears to hang
when launched from a non-interactive shell (scripts, CI, AI CLI tools). The container's
working_dir is already /var/www/cplatform/public/app_rest, so test paths are relative to it.
Run the whole suite:
docker compose -f docker-compose-dev.yml exec -T nginx vendor/bin/phpunitRun a single test file:
docker compose -f docker-compose-dev.yml exec -T nginx vendor/bin/phpunit tests/TestCase/Controller/UsersControllerTest.phpRun a single test method with --filter:
docker compose -f docker-compose-dev.yml exec -T nginx vendor/bin/phpunit --filter testAddNew tests/TestCase/Controller/UsersControllerTest.phpNotes:
- The service name is
nginx(it runs both nginx and php-fpm); there is no separatephpservice. - If the container is not running, start it first with
docker compose -f docker-compose-dev.yml up -d.
Our REST API will follow these principles:
- Statelessness: Each HTTP request contains all information needed to complete the request.
- Well-defined HTTP methods: we are using GET, POST, PATCH and DELETE (as defined in the Controllers section) to perform different CRUD operations
- Uniform interface:
- Universal syntax: Each resource should be addressed with one single URI
- The API is sending and receiving data using JSON
- HTTP response status codes. 20X codes will always be successful responses while 40X or 50X codes will be used for different errors (see list below).
- Self-explanatory: The API will use a common naming convention for URIs and include HATEOAS to improve self discovery
Running the test suite also generates an OpenAPI specification (written under app_rest/swagger-openapi/)
out of the requests and responses exercised by the controller tests. From that spec the frontend
TypeScript types are generated with orval.
For the generator to know which JSON objects are the same type (and therefore map to a single
reusable schema / TS type instead of being duplicated), every object carries a _c marker holding its
schema name (the constant is RestApiEntity::CLASS_NAME = '_c').
-
In responses the marker is added automatically by entities (via
RestApiEntity::toChild()and the swaggerStandardEntity) whenSwagger.identifyEntitiesis enabled — it is turned on during tests. -
In request bodies sent from tests you must add
_cyourself, e.g. a PATCH body:$data = [ '_c' => 'PatchRankingSettingsBody', 'max_points' => 250, // ... ];
Rules of thumb:
- The
_cvalue becomes the schema name in the spec (#/components/schemas/PatchRankingSettingsBody) and the generated TS type name. - Two payloads that share the same
_cmap to the same schema, so reuse the same_cstring whenever the payload shape is meant to be the same type (and use a different one when it is not). - The schema is assembled from the example payloads in the tests, so a request-body test should send the
full set of editable properties (not only the field under assertion) so the generated type is
complete. See
RankingSettingsControllerTest::testEditUpdatesRankingAndInvalidatesCacheas an example.
List of used HTTP status codes
Errors and success responses will be handled with standard HTTP status codes.
Error codes are handled in code throwing PHP exceptions. There are many exceptions for all common errors described below.
Some examples are BadRequestException (400), NotFoundException (404), ForbiddenException (403),
InternalErrorException (500), NotImplementedException (501), and some other exceptions with custom
behaviors like SilentException (do not add exception to logs), ValidationException
(to handle default model data validation with a 400 code), and DetailedException (the message will be displayed even in production)
| HTTP status | URL |
|---|---|
| 200 | OK |
| 201 | Created (on POST) |
| 204 | No content (on DELETE) |
| 301 | Moved permanently (redirect) |
| 302 | Found (redirect) |
| 400 | Bad Request / Data validation error (ValidationException) |
| 401 | Unauthorized (login required) |
| 403 | Forbidden (user without access to action) |
| 404 | Not found (in lists use 200 empty array) |
| 405 | Method not allowed (invalid HTTP method) |
| 409 | Conflict (in checkout) |
| 50x | Server error |
Usually a new endpoint will require a new set of related objects.
- Controller: This is where the main logic of the endpoint is located.
- Entity: This is one single object usually returned in the endpoint. Normally one entity is an object representing a database row
- Table: This is where the definition of database relations and queries are defined
- Test: All code should be tested. All different classes should have test cases, this includes controllers (which should have ControllerTests)
- Fixture: The data used to work with unit tests should be defined in fixtures.
This repository uses CakePHP MVC framework with a customized layer on top of it to work easier with Rest APIs.
Controllers will have different methods that can be overwritten to add functionality for each HTTP method.
Each different API URL must be linked to a controller.
The type data returned for each HTTP method will follow the standard described below.
A naming convention for routes and parameters in the routes are used (for example, the parameter userID will be checked against the authentication token)
Each controller must have a route defined in the BasePlugin file located in src/ directory of each plugin
or in the routes.php file (when not using plugins)
Controllers could have defined the following methods (all inherited from \RestApi\Controller\RestApiController)
- isPublicController(): optional function to define if the controller is publicly available (without authentication)
- getMandatoryParams(): mandatory function where the mandatory params should be defined, so they are checked automatically (error will be thrown if the param is not defined)
- getList(): method called when an HTTP GET request without id is delivered by the server. Used to retrieve many entities.
- getData($id): method called when an HTTP GET request WITH id is delivered by the server. Used to retrieve one entity.
- addNew($data): method called when an HTTP POST request is delivered by the server. Used to create a new entity.
- edit($id, $data): method called when an HTTP PATCH request is delivered by the server. Used to edit one entity.
- delete($id): method called when an HTTP DELETE request is delivered by the server. Used to delete one entity.
Description of HTTP methods and functions in controllers:
| HTTP method | URL | Controller Method | Description | Returns | HTTP success status |
|---|---|---|---|---|---|
| POST | /entity | addNew($data) | Create a new entity | Entity created | 201 |
| GET | /entity | getList() | Get list | List of entities | 200 |
| GET | /entity/{id} | getData($id) | Get one entity | Single entity | 200 |
| PATCH | /entity/{id} | edit($id, $data) | Edit | Entity modified | 200 |
| DELETE | /entity/{id} | delete($id) | Deletes single entity | (no content) | 204 |
| OPTIONS | * | (automatic) | (check ApiCorsComponent) | 200 | |
| PUT | /entity/{id} | put($id, $data) | Entity modified | 200 |
The model level used is the one defined by cakephp with 2 different classes (Tables and Entities).
Queries are built from tables (or if they are very simple, directly from controllers). The different queries are defined in cakephp documentation
You can run tests using phpunit command: vendor/bin/phpunit -c ../app_rest/phpunit.xml.dist
But using an IDE is desirable (e.g. PhpStorm)
Generate test coverage with: vendor/bin/phpunit --coverage-html ./webroot/coverage/*
Plugins allow to code functionalities with a logical separation between them.
Docs about plugins: plugins.md
We are working on two different databases:
phputestingfor unit testing (it will be created automatically when running tests)app_restfor local development (it will be created automatically when browsing api/v1/ping/pong)
Browsing that endpoint also runs the pending migrations, which is how a deploy applies them. Seeds are opt-in and need
?seeds=true; see the setup section above.
Migrations should be the only way to perform changes in the database schema.
Docs about migrations: migrations.md
We will use sonarqube community edition (free). For that is needed to be installed as a docker container, with the following command:
docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latestDocs about uploads: https://github.com/oreplay/oreplay-backend/blob/main/docs/upload-results.md
The server runs in a 200 MB container, and an upload is refused rather than allowed to run it out of memory. Two limits apply, both to IOF XML uploads:
| Limit | Value | What happens |
|---|---|---|
| File size | 20 MB | The upload is rejected |
| Competitors in one class (average) | 2 000 | The upload is rejected, naming the class size |
The number of competitors in the event is not the problem — the number in a single class is. A race of 20 000 people spread over 300 classes imports fine. One relay class of 6 000 does not, because the import holds a whole class in memory at once: roughly 18 kB per runner plus 4 kB per split time, so 6 000 runners with six splits each needs about 209 MB, more than the container has.
For scale: a 2 000-runner class peaks at about 81 MB and imports in around 12 seconds.
If your event hits the class limit, the message says so and asks you to split the largest class or upload classes separately. Nothing is lost and nothing crashes — the upload simply does not happen. Relays are the usual cause, because every team is in one class; ordinary individual races rarely exceed a few hundred runners in a class.
Raising the limit is not the fix, and neither is more memory: the work is to save a class in batches instead
of all at once, which would bring a 6 000-runner class to about 60 MB. It is written up as late7 in
docs/upload-summary.md, and it is worth doing when a real event needs it.