slimでknp-componentsのpaginatorを使う(データベースアクセス版2)

前回の記事ではページ捲り用のクラスを作ってページ捲り機能を実装してました。
今回はデータの取得/計算をコントローラで行いpagination機能だけを使いたい場合の例を記します。
素のphpの場合、この実装がやりやすいと思います。

Controllerの変更
リミット(limit) , 総件数(count),ページ数(page), データ(items)の取得/計算を行います。
テンプレートは前回から修正の必要はありません。

$ vi src/Taka512/Controllers/ContentsController.php
<?php
namespace Taka512\Controllers;
use Knp\Component\Pager\Pagination\SlidingPagination;

class ContentsController
{
~省略~
    public function pageTest($page) {
        $limit = 5;
        $offset = abs($page - 1) * $limit;

        $sth = $this->dbh->prepare('SELECT COUNT(*) AS count FROM alphabet');
        $sth->execute();
        $count = 0;
        while($row = $sth->fetch(\PDO::FETCH_ASSOC)){
            $count = $row['count'];
        }

        $items = array();
        if ($count) {
            $sth = $this->dbh->prepare('SELECT * FROM alphabet ORDER BY SORT LIMIT ? OFFSET ?');
            $sth->execute(array($limit, $offset));
            while($row = $sth->fetch(\PDO::FETCH_ASSOC)){
                $items[] = $row;
            }
        }

        $pagination = new SlidingPagination();
        $pagination->setCurrentPageNumber($page);
        $pagination->setItemNumberPerPage($limit);
        $pagination->setTotalItemCount($count);
        $pagination->setItems($items);
        $pagination->setCustomParameters(array());
        $pagination->setPaginatorOptions(array());
        $this->app->render('page_test.html.twig', array('pagination' => $pagination));
    }


こんな感じでknp-componentsは理解すると便利に利用できます。