Hello all,
I’ve been reading and re-reading this book, and following through building my own CMS framework upon its principles. And I’ve found a bug I can’t figure out in the last chapter.
He implements a way to order, limit and paginate the jokes. And then explains how to do the same thing within joke categories. The only trouble is it doesn’t quite work properly within the categories. The Jokes are order chronologically (newest to oldest). Within the joke categories on each paginated page the jokes are ordered chronologically but the pages themselves seem to run in the wrong order (oldest to newest).
I’ll put in a few bits of code to see if anyone can spot a problem.
CODE FROM jokes.html.php (page template)
Blockquote
<?php
$numPages = ceil($totalJokes/10);
for ($i = 1; $i <= $numPages; $i++):
if ($i == $currentPage):
?>
<a class="currentpage" href="/joke/list?page=<?=$i?><?=!empty($categoryId) ? '&category=' . $categoryId : '' ?>"><?=$i?></a>
<?php else: ?>
<a href="/joke/list?page=<?=$i?><?=!empty($categoryId) ? '&category=' . $categoryId : '' ?>"><?=$i?></a>
<?php endif; ?>
<?php endfor; ?>
CODE FROM Controllers/Joke
Blockquote
public function list() {
$page = $_GET['page'] ?? 1;
$offset = ($page-1)*10;
if (isset($_GET['category'])) {
$category = $this->categoriesTable->findById($_GET['category']);
$jokes = $category->getJokes(10, $offset);
$totalJokes = $category->getNumJokes();
}
else {
$jokes = $this->jokesTable->findAll('jokedate DESC', 10, $offset);
$totalJokes = $this->jokesTable->total();
}
$title = 'Joke list';
$author = $this->authentication->getUser();
return ['template' => 'jokes.html.php',
'title' => $title,
'variables' => [
'totalJokes' => $totalJokes,
'jokes' => $jokes,
'user' => $author,
'categories' => $this->categoriesTable->findAll(),
'currentPage' => $page,
'categoryId' => $_GET['category'] ?? null
]
];
}
CODE FROM Entity/Category
Blockquote
public function getJokes($limit = null, $offset = null) {
$jokeCategories = $this->jokeCategoriesTable->find('categoryId', $this->id, null, $limit, $offset);
$jokes = [];
foreach ($jokeCategories as $jokeCategory) {
$joke = $this->jokesTable->findById($jokeCategory->jokeId);
if ($joke) {
$jokes[] = $joke;
}
}
usort($jokes, [$this, 'sortJokes']);
return $jokes;
}
public function getNumJokes() {
return $this->jokeCategoriesTable->total('categoryId', $this->id);
}
private function sortJokes($a, $b) {
$aDate = new \DateTime($a->jokedate);
$bDate = new \DateTime($b->jokedate);
if ($aDate->getTimestamp() == $bDate->getTimestamp()) {
return 0;
}
return $aDate->getTimestamp() > $bDate->getTimestamp() ? -1 : 1;
}
Thanks for your help.
I am aware there is a new edition of the book out, but I’ve been bashing away at this edition since a fair while before that emerged, and feel I should solidify my understanding of it before updating.