MMOframework
Pourquoi l'IA Playground Bibliothèques Développeurs Agence
FR EN
Créer un projet en direct
Index
# Your first controller A JSON API: aController, #[APIRoute], the route, the answer, the order of routes. - **You will have:** `team.json`, the list of your team, filtered by the query string; `team/{id}.json`, one member or a 404; and their tests. - **You need:** **Configuration** done. ## 1. A controller is a class with routes Pages need no code: a folder of `src/pages` is enough. Anything else a url answers -- an API, a file, a form's action -- is a **controller**: a class whose methods carry a route. Create `src/controllers/TeamController.php`: ```php from=src/controllers/TeamController.php class TeamController extends aDataController { /** @var list the members of the team */ public array $members = []; ``` `aDataController` is the controller of an API: each route returns a plain array, and the framework sends it as JSON. Its `$members` are set by the configuration, like `Company`'s in the previous guide; the next guide puts them in a database. ## 2. A route A method with the `#[APIRoute]` attribute answers the urls of its pattern: the method, a `|`, the path. ```php from=src/controllers/TeamController.php #[APIRoute('GET|team.json', 'The members of the team', mediaTypes: ['json'])] public function routeList(Route $route): array { $role = (string)$route->get('role', ''); return array_values(array_filter($this->members, fn($member) => ($role === '') || ($member['role'] === $role))); } ``` The second argument describes it: it goes in the OpenAPI document the framework generates, and an AI agent reads it through the MCP server. `$route->get('role')` reads a value of the request, from the path, the query string or the body. ## 3. A parameter, and a 404 `{id}` in the pattern is a parameter, read the same way. When there is nothing to answer, throw: `e404` becomes a 404 response. ```php from=src/controllers/TeamController.php #[APIRoute('GET|team/{id}.json', 'One member of the team', mediaTypes: ['json'])] public function routeGet(Route $route): array { $id = (int)$route->get('id'); foreach ($this->members as $member) { if ($member['id'] === $id) {return ['member' => $member];} } throw new e404($this, $route, 'no member [{id}].', ['id' => $id]); } ``` ## 4. Register it, before the pages Require the class in `src/bootstrap.php`: ```php from=src/bootstrap.php require(__DIR__ . '/controllers/TeamController.php'); ``` Then add it to the application's `routes`, in `configs/config.json`, and give it its members: ```json from=configs/config.json "routes": { //the team's API: before the pages, which answer every url "AcmePortal\\controllers\\TeamController": {}, //serves every page of the Theme's `pages` below "MMO\\client\\controllers\\PageController": {} } }, // == the team == "AcmePortal\\controllers\\TeamController": { "members": [ {"id": 1, "name": "Ada Lovelace", "role": "engineering"}, {"id": 2, "name": "Grace Hopper", "role": "engineering"}, {"id": 3, "name": "Mary Jackson", "role": "sales"} ] }, ``` **The order matters.** The first controller of the list whose route matches a request answers it, alone. The PageController answers every url, so a controller listed after it is never reached. The entry in `routes` only registers the controller. Its settings go under its own class name, below: those are the ones its properties receive. ## 5. Try it ```bash php -S localhost:8000 -t www www/index.php ``` Open : ```json {"meta": [], "links": [], "data": [{"id": 3, "name": "Mary Jackson", "role": "sales"}], "logs": []} ``` What the route returned is in `data`: the answer follows the general shape of a JSON API, `meta` and `links` beside the data. In development, `logs` carries the request's log. answers 404. ## 6. Test it `tests/unit/TestTeam.php`. A test's request runs in its own process, through the same routing: ```php from=tests/unit/TestTeam.php protected function data(string $uri): mixed { return json_decode((string)$this->http('GET', $uri)->getBody(), true)['data']; } ``` ```php from=tests/unit/TestTeam.php public function testTheQueryStringFiltersIt(): void { $this->assertSame(['Mary Jackson'], array_column($this->data('team.json?role=sales'), 'name')); } public function testOneMemberOr404(): void { $this->assertSame('Grace Hopper', $this->data('team/2.json')['member']['name']); $this->assertSame(404, $this->http('GET', 'team/9.json')->getStatusCode()); } ``` ```bash phpunit ``` ## Common mistakes - **The controller after the PageController.** Its urls show a page, or a 404 page. Put it before. - **A plain `aController` returning an array.** Its routes build their own response (`Response::Html()`, `Response::Json()`); "route has no response set" means an array was returned. For an API, extend `aDataController`. - **Reading the answer at the top level.** What the route returned is under `data`. - **The class not required.** Registering it in `routes` is not enough: `src/bootstrap.php` must require it. ## Going further - Next: **Entities and a database**, where the team moves from the configuration to a table. - [Controllers](https://www.mmoframework.fr/en/documentation/mmo.core/Controller.md) and [Router](https://www.mmoframework.fr/en/documentation/mmo.core/Router.md): routes, formats and answers in detail.