ActiveDataProvider.php 6.14 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\data;

10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Query;
13
use yii\db\ActiveQuery;
14
use yii\db\Connection;
15 16

/**
17
 * ActiveDataProvider implements a data provider based on [[Query]] and [[ActiveQuery]].
18
 *
19
 * ActiveDataProvider provides data by performing DB queries using [[query]].
20
 *
21
 * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
22 23 24 25 26 27 28 29 30 31
 *
 * ~~~
 * $provider = new ActiveDataProvider(array(
 *     'query' => Post::find(),
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
32
 * $posts = $provider->getModels();
33 34
 * ~~~
 *
35 36 37
 * And the following example shows how to use ActiveDataProvider without ActiveRecord:
 *
 * ~~~
38
 * $query = new Query;
39
 * $provider = new ActiveDataProvider(array(
40
 *     'query' => $query->from('tbl_post'),
41 42 43 44 45 46
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
47
 * $posts = $provider->getModels();
48 49
 * ~~~
 *
50 51 52 53 54 55
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveDataProvider extends DataProvider
{
	/**
56
	 * @var Query the query that is used to fetch data models and [[totalCount]]
57 58 59 60
	 * if it is not explicitly set.
	 */
	public $query;
	/**
61 62
	 * @var string|callable the column that is used as the key of the data models.
	 * This can be either a column name, or a callable that returns the key value of a given data model.
63
	 *
64
	 * If this is not set, the following rules will be used to determine the keys of the data models:
65 66
	 *
	 * - If [[query]] is an [[ActiveQuery]] instance, the primary keys of [[ActiveQuery::modelClass]] will be used.
67
	 * - Otherwise, the keys of the [[models]] array will be used.
68 69
	 *
	 * @see getKeys()
70
	 */
71
	public $key;
72 73 74 75 76
	/**
	 * @var Connection|string the DB connection object or the application component ID of the DB connection.
	 * If not set, the default DB connection will be used.
	 */
	public $db;
77

78
	private $_models;
79
	private $_keys;
80
	private $_totalCount;
81

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	/**
	 * Initializes the DbCache component.
	 * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
	 * @throws InvalidConfigException if [[db]] is invalid.
	 */
	public function init()
	{
		parent::init();
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
			if (!$this->db instanceof Connection) {
				throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
			}
		}
	}

98
	/**
99 100
	 * Returns the number of data models in the current page.
	 * This is equivalent to `count($provider->models)`.
Qiang Xue committed
101
	 * When [[pagination]] is false, this is the same as [[totalCount]].
102
	 * @return integer the number of data models in the current page.
103
	 */
104
	public function getCount()
105
	{
106
		return count($this->getModels());
107 108 109
	}

	/**
110
	 * Returns the total number of data models.
Qiang Xue committed
111 112
	 * When [[pagination]] is false, this returns the same value as [[count]].
	 * If [[totalCount]] is not explicitly set, it will be calculated
113
	 * using [[query]] with a COUNT query.
114
	 * @return integer total number of possible data models.
115 116
	 * @throws InvalidConfigException
	 */
117
	public function getTotalCount()
118 119
	{
		if ($this->getPagination() === false) {
120
			return $this->getCount();
121
		} elseif ($this->_totalCount === null) {
122 123
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
124 125
			}
			$query = clone $this->query;
126
			$this->_totalCount = $query->limit(-1)->offset(-1)->count('*', $this->db);
127
		}
128
		return $this->_totalCount;
129 130 131
	}

	/**
132 133
	 * Sets the total number of data models.
	 * @param integer $value the total number of data models.
134
	 */
Qiang Xue committed
135
	public function setTotalCount($value)
136
	{
137
		$this->_totalCount = $value;
138 139 140
	}

	/**
141 142
	 * Returns the data models in the current page.
	 * @return array the list of data models in the current page.
143
	 * @throws InvalidConfigException if [[query]] is not set or invalid.
144
	 */
145
	public function getModels()
146
	{
147
		if ($this->_models === null) {
148 149 150 151 152 153 154 155
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
			}
			if (($pagination = $this->getPagination()) !== false) {
				$pagination->totalCount = $this->getTotalCount();
				$this->query->limit($pagination->getLimit())->offset($pagination->getOffset());
			}
			if (($sort = $this->getSort()) !== false) {
156
				$this->query->addOrderBy($sort->getOrders());
157 158
			}
			$this->_models = $this->query->all($this->db);
159
		}
160
		return $this->_models;
161 162 163
	}

	/**
164 165
	 * Returns the key values associated with the data models.
	 * @return array the list of key values corresponding to [[models]]. Each data model in [[models]]
166 167
	 * is uniquely identified by the corresponding key value in this array.
	 */
168
	public function getKeys()
169
	{
170
		if ($this->_keys === null) {
171
			$this->_keys = array();
172
			$models = $this->getModels();
173
			if ($this->key !== null) {
174
				foreach ($models as $model) {
175
					if (is_string($this->key)) {
176
						$this->_keys[] = $model[$this->key];
177
					} else {
178
						$this->_keys[] = call_user_func($this->key, $model);
179 180 181
					}
				}
			} elseif ($this->query instanceof ActiveQuery) {
182 183 184 185 186
				/** @var \yii\db\ActiveRecord $class */
				$class = $this->query->modelClass;
				$pks = $class::primaryKey();
				if (count($pks) === 1) {
					$pk = $pks[0];
187 188
					foreach ($models as $model) {
						$this->_keys[] = $model[$pk];
189 190
					}
				} else {
191
					foreach ($models as $model) {
192 193
						$keys = array();
						foreach ($pks as $pk) {
194
							$keys[] = $model[$pk];
195 196 197 198 199
						}
						$this->_keys[] = json_encode($keys);
					}
				}
			} else {
200
				$this->_keys = array_keys($models);
201 202 203 204
			}
		}
		return $this->_keys;
	}
205 206

	/**
207 208 209
	 * Refreshes the data provider.
	 * After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
	 * they will re-execute the query and return the latest data available.
210
	 */
211
	public function refresh()
212
	{
213 214 215
		$this->_models = null;
		$this->_totalCount = null;
		$this->_keys = null;
216
	}
217
}