API Posts
Posts and authors fetched from JSONPlaceholder by the controller, then rendered here.
How it works
Controller fetches, template renders
PagesController::pageDemosPosts() calls the JSONPlaceholder API using
Cake\Http\Client, maps users by ID, and passes both arrays to this template
via $this->set().
src/Controller/PagesController.php
public function pageDemosPosts(): void
{
$page = max(1, (int)$this->request->getQuery('page', 1));
$perPage = 9;
$http = new Client(['timeout' => 5]);
$postsResp = $http->get('https://jsonplaceholder.typicode.com/posts', [
'_limit' => $perPage,
'_start' => ($page - 1) * $perPage,
]);
$usersResp = $http->get('https://jsonplaceholder.typicode.com/users');
foreach ((array)$usersResp->getJson() as $user) {
$userMap[(int)$user['id']] = $user;
}
$total = (int)$postsResp->getHeaderLine('X-Total-Count');
$totalPages = (int)ceil($total / $perPage);
$this->set(compact('posts', 'userMap', 'error', 'page', 'totalPages'));
}
Live data
Posts from JSONPlaceholder
No posts returned.