Pagine la liste des news récentes
This commit is contained in:
@@ -6,13 +6,21 @@ namespace Silex\Controller;
|
||||
|
||||
use Silex\DI\DI;
|
||||
use Silex\Http\HttpResponse;
|
||||
use Silex\Util\Pagination;
|
||||
|
||||
class UserController
|
||||
{
|
||||
public function index(DI $di): HttpResponse
|
||||
private const PER_PAGE = 12;
|
||||
|
||||
public function index(DI $di, array $params): HttpResponse
|
||||
{
|
||||
$news = $di->getNewsGateway()->getPaginatedRecentNews();
|
||||
return new HttpResponse(200, 'home', ['news' => $news]);
|
||||
$gw = $di->getNewsGateway();
|
||||
|
||||
$page = intval($params['page'] ?? 1);
|
||||
$total = $gw->getCount();
|
||||
$nbPages = Pagination::getNbPages($total, self::PER_PAGE);
|
||||
$news = $gw->getPaginatedRecentNews($page , self::PER_PAGE);
|
||||
return new HttpResponse(200, 'home', ['news' => $news, 'page' => $page, 'nbPages' => $nbPages, 'router' => $di->getRouter()]);
|
||||
}
|
||||
|
||||
public function viewPost(DI $di, array $params): HttpResponse
|
||||
|
@@ -37,6 +37,15 @@ class NewsGateway
|
||||
return $news;
|
||||
}
|
||||
|
||||
public function getCount(): int
|
||||
{
|
||||
$req = $this->pdo->query('SELECT COUNT(*) nb FROM news;');
|
||||
if ($req === false) {
|
||||
return 0;
|
||||
}
|
||||
return intval($req->fetch()['nb']);
|
||||
}
|
||||
|
||||
public function getById(int $id): News
|
||||
{
|
||||
$req = $this->pdo->prepare('SELECT * FROM news WHERE id_news=:id;');
|
||||
|
13
src/Silex/Util/Pagination.php
Normal file
13
src/Silex/Util/Pagination.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Silex\Util;
|
||||
|
||||
final class Pagination
|
||||
{
|
||||
public static function getNbPages(int $nbItems, int $perPage): int
|
||||
{
|
||||
return intval(ceil($nbItems / $perPage));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user