在我的应用程序中,我想使用 Zend Framework 2 的分页器。我面临的问题是我从表而不是数组中获取对象结果集。
我可以通过使用 foreach 遍历对象并生成一个新数组来简单地解决这个问题。但在我看来,这是一种解决方法,完全没有必要这样做。
我为我的桌子准备的代码:
VideosTable.php
namespace Application\Model;
use Zend\Db\Sql\Expression;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Application\Model\Videos;
class VideosTable extends AbstractTableGateway
{
protected $table = 'videos';
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Videos());
$this->initialize();
}
/**
* Get movie list
*/
public function getMovies($limit, $order, $array = null)
{
$select = new Select();
$select->from($this->table);
$select->order('id', $order)->limit($limit);
$resultSet = $this->selectWith($select);
return $resultSet;
}
}
我在控制器中设置的分页器:
public function indexAction()
{
$select = new Select();
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$videos = $this->getVideosTable()->getMovies(25, 'DESC');
// could do like this but looks not necessary / dirty
foreach ($videos as $key => $video) :
$data[] = array('video_title' => $video->video_title);
endforeach;
$paginator = new Paginator(new \Zend\Paginator\Adapter\ArrayAdapter($data));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage(11)
->setPageRange(7);
etc..
提前致谢,
缺口