Zend Framework 2 Paginator + TableGateway

The*_*per 2 zend-db zend-paginator zend-framework2 tablegateway

如何将数据库映射器与paginator一起使用?

我在理解如何使用下面的代码实现DbSelect paginator时遇到了一些麻烦(现在它正在使用Iterator适配器,它不适用于ResultSet).

据我所知,它并不像我希望的那样直截了当.DbSelect期待一个Zend\Db\Sql\Select和一个适配器.适配器是一个非问题,可以使用以下方法检索:

$this->newsContents()->getAdapter()
Run Code Online (Sandbox Code Playgroud)

但我无法Select从我的TableGateway中获取一个对象而不重复我的查询代码.有没有简单的方法来解决这个问题?

NewsController.php

<?php

namespace News\Controller;

use Zend\Paginator\Paginator;

class NewsController extends \Application\Controller\WebsiteController
{
    protected $newsTable;

    protected $newsContents;

    protected function newsTable()
    {
        return $this->getServiceLocator()->get('News\Model\NewsTable');
    }

    protected function newsContents()
    {
        return $this->getServiceLocator()->get('News\Model\NewsContentsTable');
    }

    protected function articleId()
    {
        return (int) $this->params()->fromRoute('id');
    }

    public function articleAction()
    {
        $article = $this->newsTable()->getArticle($this->articleId());
        $pages   = $this->newsContents()->getPages($this->articleId());

        $paginator = new Paginator(new \Zend\Paginator\Adapter\Iterator($pages));
        $paginator->setCurrentPageNumber($this->params()->fromRoute('page'));

        return array(
            'css'       => 'news.css',
            'article'   => $article,
            'paginator' => $paginator,
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

NewsContentsTable.php

<?php

namespace News\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;

class NewsContentsTable extends \Zend\Db\TableGateway\AbstractTableGateway
{
    protected $table = 'news_contents';

    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet;
        $this->resultSetPrototype->setArrayObjectPrototype(new NewsContents);
        $this->initialize();
    }

    public function getPages($newsId)
    {
        $rowset = $this->select(function(Select $select) use ($newsId)
        {
            $select
                ->order('order ASC')
                ->where(array('news_id' => $newsId));
        });

        return $rowset;
    }

}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ski 7

从Zend Framework 2.2开始,它更容易(并且让您充分享受TableGateway提供的优势) - 您应该使用它

use Zend\Db\TableGateway\TableGateway;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\DbTableGateway;  // !!!

 
$dbTableGatewayAdapter = new DbTableGateway($this->tableGateway);
$paginator = new Paginator($dbTableGatewayAdapter);
return $paginator;
Run Code Online (Sandbox Code Playgroud)