如何将数据库映射器与分页器一起使用?
我在理解如何使用下面的代码实现 DbSelect 分页器时遇到了一些麻烦(现在它正在使用不适用于 ResultSets 的 Iterator 适配器)。
据我所知,这并不像我希望的那样直截了当。DbSelect 需要一个Zend\Db\Sql\Select
和一个适配器。适配器不是问题,可以通过以下方式检索:
$this->newsContents()->getAdapter()
但我无法在Select
不复制查询代码的情况下从 TableGateway 中取出对象。有没有简单的方法来解决这个问题?
新闻控制器.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,
);
}
}
新闻内容表.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;
}
}