0

在我的应用程序中,我想使用 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..

提前致谢,

缺口

4

1 回答 1

1

更改您的 getMovies 方法以返回类似这样的内容

/**
 * Get movie list
 */
public function getMovies($limit, $order, $array = null)
{
    $select = new Select();
    $select->from($this->table);
    $select->order('id', $order)->limit($limit);

    return new \Zend\Paginator\Paginator(
        new \Zend\Paginator\Adapter\DbSelect($select, $this->adapter, $this->resultSetPrototype)
    );
}

然后,您可以在控制器中使用该分页器随心所欲地进行操作。它还允许您从 getMovies() 方法中放弃该限制逻辑,因为它将由分页器处理。

放弃限制逻辑(因为它由分页器处理)看起来像这样

/**
 * Get movie list
 */
public function getMovies($order = 'DESC')
{
    $select = $this->getSql()->select();
    $select->order('id', $order);

    return new \Zend\Paginator\Paginator(
        new \Zend\Paginator\Adapter\DbSelect($select, $this->adapter, $this->resultSetPrototype)
    );
}
于 2013-09-12T23:02:58.430 回答