3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Paginator\Adapter
;
12 use Zend\Db\Adapter\Adapter
;
14 use Zend\Db\Sql\Expression
;
15 use Zend\Db\Sql\Select
;
16 use Zend\Db\ResultSet\ResultSet
;
17 use Zend\Db\ResultSet\ResultSetInterface
;
19 class DbSelect
implements AdapterInterface
25 protected $sql = null;
32 protected $select = null;
37 protected $resultSetPrototype = null;
44 protected $rowCount = null;
49 * @param Select $select The select query
50 * @param Adapter|Sql $adapterOrSqlObject DB adapter or Sql object
51 * @param null|ResultSetInterface $resultSetPrototype
52 * @throws Exception\InvalidArgumentException
54 public function __construct(Select
$select, $adapterOrSqlObject, ResultSetInterface
$resultSetPrototype = null)
56 $this->select
= $select;
58 if ($adapterOrSqlObject instanceof Adapter
) {
59 $adapterOrSqlObject = new Sql($adapterOrSqlObject);
62 if (!$adapterOrSqlObject instanceof Sql
) {
63 throw new Exception\
InvalidArgumentException(
64 '$adapterOrSqlObject must be an instance of Zend\Db\Adapter\Adapter or Zend\Db\Sql\Sql'
68 $this->sql
= $adapterOrSqlObject;
69 $this->resultSetPrototype
= ($resultSetPrototype) ?
: new ResultSet
;
73 * Returns an array of items for a page.
75 * @param int $offset Page offset
76 * @param int $itemCountPerPage Number of items per page
79 public function getItems($offset, $itemCountPerPage)
81 $select = clone $this->select
;
82 $select->offset($offset);
83 $select->limit($itemCountPerPage);
85 $statement = $this->sql
->prepareStatementForSqlObject($select);
86 $result = $statement->execute();
88 $resultSet = clone $this->resultSetPrototype
;
89 $resultSet->initialize($result);
95 * Returns the total number of rows in the result set.
99 public function count()
101 if ($this->rowCount
!== null) {
102 return $this->rowCount
;
105 $select = clone $this->select
;
106 $select->reset(Select
::LIMIT
);
107 $select->reset(Select
::OFFSET
);
108 $select->reset(Select
::ORDER
);
110 $countSelect = new Select
;
111 $countSelect->columns(array('c' => new Expression('COUNT(1)')));
112 $countSelect->from(array('original_select' => $select));
114 $statement = $this->sql
->prepareStatementForSqlObject($countSelect);
115 $result = $statement->execute();
116 $row = $result->current();
118 $this->rowCount
= $row['c'];
120 return $this->rowCount
;