Complex classes like BaseActiveRecord often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use BaseActiveRecord, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
43 | abstract class BaseActiveRecord extends Model implements ActiveRecordInterface |
||
44 | { |
||
45 | /** |
||
46 | * @event Event an event that is triggered when the record is initialized via [[init()]]. |
||
47 | */ |
||
48 | const EVENT_INIT = 'init'; |
||
49 | /** |
||
50 | * @event Event an event that is triggered after the record is created and populated with query result. |
||
51 | */ |
||
52 | const EVENT_AFTER_FIND = 'afterFind'; |
||
53 | /** |
||
54 | * @event ModelEvent an event that is triggered before inserting a record. |
||
55 | * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion. |
||
56 | */ |
||
57 | const EVENT_BEFORE_INSERT = 'beforeInsert'; |
||
58 | /** |
||
59 | * @event AfterSaveEvent an event that is triggered after a record is inserted. |
||
60 | */ |
||
61 | const EVENT_AFTER_INSERT = 'afterInsert'; |
||
62 | /** |
||
63 | * @event ModelEvent an event that is triggered before updating a record. |
||
64 | * You may set [[ModelEvent::isValid]] to be `false` to stop the update. |
||
65 | */ |
||
66 | const EVENT_BEFORE_UPDATE = 'beforeUpdate'; |
||
67 | /** |
||
68 | * @event AfterSaveEvent an event that is triggered after a record is updated. |
||
69 | */ |
||
70 | const EVENT_AFTER_UPDATE = 'afterUpdate'; |
||
71 | /** |
||
72 | * @event ModelEvent an event that is triggered before deleting a record. |
||
73 | * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion. |
||
74 | */ |
||
75 | const EVENT_BEFORE_DELETE = 'beforeDelete'; |
||
76 | /** |
||
77 | * @event Event an event that is triggered after a record is deleted. |
||
78 | */ |
||
79 | const EVENT_AFTER_DELETE = 'afterDelete'; |
||
80 | /** |
||
81 | * @event Event an event that is triggered after a record is refreshed. |
||
82 | * @since 2.0.8 |
||
83 | */ |
||
84 | const EVENT_AFTER_REFRESH = 'afterRefresh'; |
||
85 | |||
86 | /** |
||
87 | * @var array attribute values indexed by attribute names |
||
88 | */ |
||
89 | private $_attributes = []; |
||
90 | /** |
||
91 | * @var array|null old attribute values indexed by attribute names. |
||
92 | * This is `null` if the record [[isNewRecord|is new]]. |
||
93 | */ |
||
94 | private $_oldAttributes; |
||
95 | /** |
||
96 | * @var array related models indexed by the relation names |
||
97 | */ |
||
98 | private $_related = []; |
||
99 | |||
100 | |||
101 | /** |
||
102 | * @inheritdoc |
||
103 | * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches. |
||
104 | */ |
||
105 | 173 | public static function findOne($condition) |
|
109 | |||
110 | /** |
||
111 | * @inheritdoc |
||
112 | * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches. |
||
113 | */ |
||
114 | public static function findAll($condition) |
||
118 | |||
119 | /** |
||
120 | * Finds ActiveRecord instance(s) by the given condition. |
||
121 | * This method is internally called by [[findOne()]] and [[findAll()]]. |
||
122 | * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter |
||
123 | * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance. |
||
124 | * @throws InvalidConfigException if there is no primary key defined |
||
125 | * @internal |
||
126 | */ |
||
127 | protected static function findByCondition($condition) |
||
128 | { |
||
129 | $query = static::find(); |
||
130 | |||
131 | if (!ArrayHelper::isAssociative($condition)) { |
||
132 | // query by primary key |
||
133 | $primaryKey = static::primaryKey(); |
||
134 | if (isset($primaryKey[0])) { |
||
135 | // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values |
||
136 | $condition = [$primaryKey[0] => is_array($condition) ? array_values($condition) : $condition]; |
||
137 | } else { |
||
138 | throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.'); |
||
139 | } |
||
140 | } |
||
141 | |||
142 | return $query->andWhere($condition); |
||
143 | } |
||
144 | |||
145 | /** |
||
146 | * Updates the whole table using the provided attribute values and conditions. |
||
147 | * |
||
148 | * For example, to change the status to be 1 for all customers whose status is 2: |
||
149 | * |
||
150 | * ```php |
||
151 | * Customer::updateAll(['status' => 1], 'status = 2'); |
||
152 | * ``` |
||
153 | * |
||
154 | * @param array $attributes attribute values (name-value pairs) to be saved into the table |
||
155 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
156 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
157 | * @return int the number of rows updated |
||
158 | * @throws NotSupportedException if not overridden |
||
159 | */ |
||
160 | public static function updateAll($attributes, $condition = '') |
||
164 | |||
165 | /** |
||
166 | * Updates the whole table using the provided counter changes and conditions. |
||
167 | * |
||
168 | * For example, to increment all customers' age by 1, |
||
169 | * |
||
170 | * ```php |
||
171 | * Customer::updateAllCounters(['age' => 1]); |
||
172 | * ``` |
||
173 | * |
||
174 | * @param array $counters the counters to be updated (attribute name => increment value). |
||
175 | * Use negative values if you want to decrement the counters. |
||
176 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
177 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
178 | * @return int the number of rows updated |
||
179 | * @throws NotSupportedException if not overrided |
||
180 | */ |
||
181 | public static function updateAllCounters($counters, $condition = '') |
||
182 | { |
||
183 | throw new NotSupportedException(__METHOD__ . ' is not supported.'); |
||
184 | } |
||
185 | |||
186 | /** |
||
187 | * Deletes rows in the table using the provided conditions. |
||
188 | * WARNING: If you do not specify any condition, this method will delete ALL rows in the table. |
||
189 | * |
||
190 | * For example, to delete all customers whose status is 3: |
||
191 | * |
||
192 | * ```php |
||
193 | * Customer::deleteAll('status = 3'); |
||
194 | * ``` |
||
195 | * |
||
196 | * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL. |
||
197 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
198 | * @return int the number of rows deleted |
||
199 | * @throws NotSupportedException if not overridden. |
||
200 | */ |
||
201 | public static function deleteAll($condition = null) |
||
202 | { |
||
203 | throw new NotSupportedException(__METHOD__ . ' is not supported.'); |
||
204 | } |
||
205 | |||
206 | /** |
||
207 | * Returns the name of the column that stores the lock version for implementing optimistic locking. |
||
208 | * |
||
209 | * Optimistic locking allows multiple users to access the same record for edits and avoids |
||
210 | * potential conflicts. In case when a user attempts to save the record upon some staled data |
||
211 | * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown, |
||
212 | * and the update or deletion is skipped. |
||
213 | * |
||
214 | * Optimistic locking is only supported by [[update()]] and [[delete()]]. |
||
215 | * |
||
216 | * To use Optimistic locking: |
||
217 | * |
||
218 | * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`. |
||
219 | * Override this method to return the name of this column. |
||
220 | * 2. Add a `required` validation rule for the version column to ensure the version value is submitted. |
||
221 | * 3. In the Web form that collects the user input, add a hidden field that stores |
||
222 | * the lock version of the recording being updated. |
||
223 | * 4. In the controller action that does the data updating, try to catch the [[StaleObjectException]] |
||
224 | * and implement necessary business logic (e.g. merging the changes, prompting stated data) |
||
225 | * to resolve the conflict. |
||
226 | * |
||
227 | * @return string the column name that stores the lock version of a table row. |
||
228 | * If `null` is returned (default implemented), optimistic locking will not be supported. |
||
229 | */ |
||
230 | 19 | public function optimisticLock() |
|
231 | { |
||
232 | 19 | return null; |
|
233 | } |
||
234 | |||
235 | /** |
||
236 | * @inheritdoc |
||
237 | */ |
||
238 | 3 | public function canGetProperty($name, $checkVars = true, $checkBehaviors = true) |
|
239 | { |
||
240 | 3 | if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) { |
|
241 | 3 | return true; |
|
242 | } |
||
243 | |||
244 | try { |
||
245 | 3 | return $this->hasAttribute($name); |
|
246 | } catch (\Exception $e) { |
||
247 | // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used |
||
248 | return false; |
||
249 | } |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * @inheritdoc |
||
254 | */ |
||
255 | 9 | public function canSetProperty($name, $checkVars = true, $checkBehaviors = true) |
|
256 | { |
||
257 | 9 | if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) { |
|
258 | 6 | return true; |
|
259 | } |
||
260 | |||
261 | try { |
||
262 | 3 | return $this->hasAttribute($name); |
|
263 | } catch (\Exception $e) { |
||
264 | // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used |
||
265 | return false; |
||
266 | } |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * PHP getter magic method. |
||
271 | * This method is overridden so that attributes and related objects can be accessed like properties. |
||
272 | * |
||
273 | * @param string $name property name |
||
274 | * @throws \yii\base\InvalidParamException if relation name is wrong |
||
275 | * @return mixed property value |
||
276 | * @see getAttribute() |
||
277 | */ |
||
278 | 314 | public function __get($name) |
|
279 | { |
||
280 | 314 | if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) { |
|
281 | 293 | return $this->_attributes[$name]; |
|
282 | 168 | } elseif ($this->hasAttribute($name)) { |
|
283 | 35 | return null; |
|
284 | } |
||
285 | |||
286 | 145 | if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) { |
|
287 | 81 | return $this->_related[$name]; |
|
288 | } |
||
289 | 100 | $value = parent::__get($name); |
|
290 | 100 | if ($value instanceof ActiveQueryInterface) { |
|
291 | 55 | return $this->_related[$name] = $value->findFor($name, $this); |
|
292 | } |
||
293 | |||
294 | 51 | return $value; |
|
295 | } |
||
296 | |||
297 | /** |
||
298 | * PHP setter magic method. |
||
299 | * This method is overridden so that AR attributes can be accessed like properties. |
||
300 | * @param string $name property name |
||
301 | * @param mixed $value property value |
||
302 | */ |
||
303 | 155 | public function __set($name, $value) |
|
304 | { |
||
305 | 155 | if ($this->hasAttribute($name)) { |
|
306 | 155 | $this->_attributes[$name] = $value; |
|
307 | } else { |
||
308 | 4 | parent::__set($name, $value); |
|
309 | } |
||
310 | 155 | } |
|
311 | |||
312 | /** |
||
313 | * Checks if a property value is null. |
||
314 | * This method overrides the parent implementation by checking if the named attribute is `null` or not. |
||
315 | * @param string $name the property name or the event name |
||
316 | * @return bool whether the property value is null |
||
317 | */ |
||
318 | 56 | public function __isset($name) |
|
319 | { |
||
320 | try { |
||
321 | 56 | return $this->__get($name) !== null; |
|
322 | } catch (\Exception $e) { |
||
323 | return false; |
||
324 | } |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Sets a component property to be null. |
||
329 | * This method overrides the parent implementation by clearing |
||
330 | * the specified attribute value. |
||
331 | * @param string $name the property name or the event name |
||
332 | */ |
||
333 | 9 | public function __unset($name) |
|
334 | { |
||
335 | 9 | if ($this->hasAttribute($name)) { |
|
336 | 3 | unset($this->_attributes[$name]); |
|
337 | 6 | } elseif (array_key_exists($name, $this->_related)) { |
|
338 | 6 | unset($this->_related[$name]); |
|
339 | } elseif ($this->getRelation($name, false) === null) { |
||
340 | parent::__unset($name); |
||
341 | } |
||
342 | 9 | } |
|
343 | |||
344 | /** |
||
345 | * Declares a `has-one` relation. |
||
346 | * The declaration is returned in terms of a relational [[ActiveQuery]] instance |
||
347 | * through which the related record can be queried and retrieved back. |
||
348 | * |
||
349 | * A `has-one` relation means that there is at most one related record matching |
||
350 | * the criteria set by this relation, e.g., a customer has one country. |
||
351 | * |
||
352 | * For example, to declare the `country` relation for `Customer` class, we can write |
||
353 | * the following code in the `Customer` class: |
||
354 | * |
||
355 | * ```php |
||
356 | * public function getCountry() |
||
357 | * { |
||
358 | * return $this->hasOne(Country::className(), ['id' => 'country_id']); |
||
359 | * } |
||
360 | * ``` |
||
361 | * |
||
362 | * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name |
||
363 | * in the related class `Country`, while the 'country_id' value refers to an attribute name |
||
364 | * in the current AR class. |
||
365 | * |
||
366 | * Call methods declared in [[ActiveQuery]] to further customize the relation. |
||
367 | * |
||
368 | * @param string $class the class name of the related record |
||
369 | * @param array $link the primary-foreign key constraint. The keys of the array refer to |
||
370 | * the attributes of the record associated with the `$class` model, while the values of the |
||
371 | * array refer to the corresponding attributes in **this** AR class. |
||
372 | * @return ActiveQueryInterface the relational query object. |
||
373 | */ |
||
374 | 52 | public function hasOne($class, $link) |
|
375 | { |
||
376 | 52 | return $this->createRelationQuery($class, $link, false); |
|
377 | } |
||
378 | |||
379 | /** |
||
380 | * Declares a `has-many` relation. |
||
381 | * The declaration is returned in terms of a relational [[ActiveQuery]] instance |
||
382 | * through which the related record can be queried and retrieved back. |
||
383 | * |
||
384 | * A `has-many` relation means that there are multiple related records matching |
||
385 | * the criteria set by this relation, e.g., a customer has many orders. |
||
386 | * |
||
387 | * For example, to declare the `orders` relation for `Customer` class, we can write |
||
388 | * the following code in the `Customer` class: |
||
389 | * |
||
390 | * ```php |
||
391 | * public function getOrders() |
||
392 | * { |
||
393 | * return $this->hasMany(Order::className(), ['customer_id' => 'id']); |
||
394 | * } |
||
395 | * ``` |
||
396 | * |
||
397 | * Note that in the above, the 'customer_id' key in the `$link` parameter refers to |
||
398 | * an attribute name in the related class `Order`, while the 'id' value refers to |
||
399 | * an attribute name in the current AR class. |
||
400 | * |
||
401 | * Call methods declared in [[ActiveQuery]] to further customize the relation. |
||
402 | * |
||
403 | * @param string $class the class name of the related record |
||
404 | * @param array $link the primary-foreign key constraint. The keys of the array refer to |
||
405 | * the attributes of the record associated with the `$class` model, while the values of the |
||
406 | * array refer to the corresponding attributes in **this** AR class. |
||
407 | * @return ActiveQueryInterface the relational query object. |
||
408 | */ |
||
409 | 135 | public function hasMany($class, $link) |
|
410 | { |
||
411 | 135 | return $this->createRelationQuery($class, $link, true); |
|
412 | } |
||
413 | |||
414 | /** |
||
415 | * Creates a query instance for `has-one` or `has-many` relation. |
||
416 | * @param string $class the class name of the related record. |
||
417 | * @param array $link the primary-foreign key constraint. |
||
418 | * @param bool $multiple whether this query represents a relation to more than one record. |
||
419 | * @return ActiveQueryInterface the relational query object. |
||
420 | * @since 2.0.12 |
||
421 | * @see hasOne() |
||
422 | * @see hasMany() |
||
423 | */ |
||
424 | 145 | protected function createRelationQuery($class, $link, $multiple) |
|
425 | { |
||
426 | /* @var $class ActiveRecordInterface */ |
||
427 | /* @var $query ActiveQuery */ |
||
428 | 145 | $query = $class::find(); |
|
429 | 145 | $query->primaryModel = $this; |
|
430 | 145 | $query->link = $link; |
|
431 | 145 | $query->multiple = $multiple; |
|
432 | 145 | return $query; |
|
433 | } |
||
434 | |||
435 | /** |
||
436 | * Populates the named relation with the related records. |
||
437 | * Note that this method does not check if the relation exists or not. |
||
438 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
439 | * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation. |
||
440 | * @see getRelation() |
||
441 | */ |
||
442 | 102 | public function populateRelation($name, $records) |
|
446 | |||
447 | /** |
||
448 | * Check whether the named relation has been populated with records. |
||
449 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
450 | * @return bool whether relation has been populated with records. |
||
451 | * @see getRelation() |
||
452 | */ |
||
453 | 42 | public function isRelationPopulated($name) |
|
457 | |||
458 | /** |
||
459 | * Returns all populated related records. |
||
460 | * @return array an array of related records indexed by relation names. |
||
461 | * @see getRelation() |
||
462 | */ |
||
463 | 6 | public function getRelatedRecords() |
|
467 | |||
468 | /** |
||
469 | * Returns a value indicating whether the model has an attribute with the specified name. |
||
470 | * @param string $name the name of the attribute |
||
471 | * @return bool whether the model has an attribute with the specified name. |
||
472 | */ |
||
473 | 255 | public function hasAttribute($name) |
|
477 | |||
478 | /** |
||
479 | * Returns the named attribute value. |
||
480 | * If this record is the result of a query and the attribute is not loaded, |
||
481 | * `null` will be returned. |
||
482 | * @param string $name the attribute name |
||
483 | * @return mixed the attribute value. `null` if the attribute is not set or does not exist. |
||
484 | * @see hasAttribute() |
||
485 | */ |
||
486 | public function getAttribute($name) |
||
490 | |||
491 | /** |
||
492 | * Sets the named attribute value. |
||
493 | * @param string $name the attribute name |
||
494 | * @param mixed $value the attribute value. |
||
495 | * @throws InvalidParamException if the named attribute does not exist. |
||
496 | * @see hasAttribute() |
||
497 | */ |
||
498 | 71 | public function setAttribute($name, $value) |
|
506 | |||
507 | /** |
||
508 | * Returns the old attribute values. |
||
509 | * @return array the old attribute values (name-value pairs) |
||
510 | */ |
||
511 | public function getOldAttributes() |
||
515 | |||
516 | /** |
||
517 | * Sets the old attribute values. |
||
518 | * All existing old attribute values will be discarded. |
||
519 | * @param array|null $values old attribute values to be set. |
||
520 | * If set to `null` this record is considered to be [[isNewRecord|new]]. |
||
521 | */ |
||
522 | 88 | public function setOldAttributes($values) |
|
526 | |||
527 | /** |
||
528 | * Returns the old value of the named attribute. |
||
529 | * If this record is the result of a query and the attribute is not loaded, |
||
530 | * `null` will be returned. |
||
531 | * @param string $name the attribute name |
||
532 | * @return mixed the old attribute value. `null` if the attribute is not loaded before |
||
533 | * or does not exist. |
||
534 | * @see hasAttribute() |
||
535 | */ |
||
536 | public function getOldAttribute($name) |
||
537 | { |
||
538 | return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; |
||
540 | |||
541 | /** |
||
542 | * Sets the old value of the named attribute. |
||
543 | * @param string $name the attribute name |
||
544 | * @param mixed $value the old attribute value. |
||
545 | * @throws InvalidParamException if the named attribute does not exist. |
||
546 | * @see hasAttribute() |
||
547 | */ |
||
548 | public function setOldAttribute($name, $value) |
||
556 | |||
557 | /** |
||
558 | * Marks an attribute dirty. |
||
559 | * This method may be called to force updating a record when calling [[update()]], |
||
560 | * even if there is no change being made to the record. |
||
561 | * @param string $name the attribute name |
||
562 | */ |
||
563 | public function markAttributeDirty($name) |
||
567 | |||
568 | /** |
||
569 | * Returns a value indicating whether the named attribute has been changed. |
||
570 | * @param string $name the name of the attribute. |
||
571 | * @param bool $identical whether the comparison of new and old value is made for |
||
572 | * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison. |
||
573 | * This parameter is available since version 2.0.4. |
||
574 | * @return bool whether the attribute has been changed |
||
575 | */ |
||
576 | 2 | public function isAttributeChanged($name, $identical = true) |
|
588 | |||
589 | /** |
||
590 | * Returns the attribute values that have been modified since they are loaded or saved most recently. |
||
591 | * |
||
592 | * The comparison of new and old values is made for identical values using `===`. |
||
593 | * |
||
594 | * @param string[]|null $names the names of the attributes whose values may be returned if they are |
||
595 | * changed recently. If null, [[attributes()]] will be used. |
||
596 | * @return array the changed attribute values (name-value pairs) |
||
597 | */ |
||
598 | 98 | public function getDirtyAttributes($names = null) |
|
621 | |||
622 | /** |
||
623 | * Saves the current record. |
||
624 | * |
||
625 | * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]] |
||
626 | * when [[isNewRecord]] is `false`. |
||
627 | * |
||
628 | * For example, to save a customer record: |
||
629 | * |
||
630 | * ```php |
||
631 | * $customer = new Customer; // or $customer = Customer::findOne($id); |
||
632 | * $customer->name = $name; |
||
633 | * $customer->email = $email; |
||
634 | * $customer->save(); |
||
635 | * ``` |
||
636 | * |
||
637 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
638 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
639 | * will not be saved to the database and this method will return `false`. |
||
640 | * @param array $attributeNames list of attribute names that need to be saved. Defaults to null, |
||
641 | * meaning all attributes that are loaded from DB will be saved. |
||
642 | * @return bool whether the saving succeeded (i.e. no validation errors occurred). |
||
643 | */ |
||
644 | 92 | public function save($runValidation = true, $attributeNames = null) |
|
652 | |||
653 | /** |
||
654 | * Saves the changes to this active record into the associated database table. |
||
655 | * |
||
656 | * This method performs the following steps in order: |
||
657 | * |
||
658 | * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]] |
||
659 | * returns `false`, the rest of the steps will be skipped; |
||
660 | * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation |
||
661 | * failed, the rest of the steps will be skipped; |
||
662 | * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`, |
||
663 | * the rest of the steps will be skipped; |
||
664 | * 4. save the record into database. If this fails, it will skip the rest of the steps; |
||
665 | * 5. call [[afterSave()]]; |
||
666 | * |
||
667 | * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]], |
||
668 | * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]] |
||
669 | * will be raised by the corresponding methods. |
||
670 | * |
||
671 | * Only the [[dirtyAttributes|changed attribute values]] will be saved into database. |
||
672 | * |
||
673 | * For example, to update a customer record: |
||
674 | * |
||
675 | * ```php |
||
676 | * $customer = Customer::findOne($id); |
||
677 | * $customer->name = $name; |
||
678 | * $customer->email = $email; |
||
679 | * $customer->update(); |
||
680 | * ``` |
||
681 | * |
||
682 | * Note that it is possible the update does not affect any row in the table. |
||
683 | * In this case, this method will return 0. For this reason, you should use the following |
||
684 | * code to check if update() is successful or not: |
||
685 | * |
||
686 | * ```php |
||
687 | * if ($customer->update() !== false) { |
||
688 | * // update successful |
||
689 | * } else { |
||
690 | * // update failed |
||
691 | * } |
||
692 | * ``` |
||
693 | * |
||
694 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
695 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
696 | * will not be saved to the database and this method will return `false`. |
||
697 | * @param array $attributeNames list of attribute names that need to be saved. Defaults to null, |
||
698 | * meaning all attributes that are loaded from DB will be saved. |
||
699 | * @return int|false the number of rows affected, or `false` if validation fails |
||
700 | * or [[beforeSave()]] stops the updating process. |
||
701 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
702 | * being updated is outdated. |
||
703 | * @throws Exception in case update failed. |
||
704 | */ |
||
705 | public function update($runValidation = true, $attributeNames = null) |
||
713 | |||
714 | /** |
||
715 | * Updates the specified attributes. |
||
716 | * |
||
717 | * This method is a shortcut to [[update()]] when data validation is not needed |
||
718 | * and only a small set attributes need to be updated. |
||
719 | * |
||
720 | * You may specify the attributes to be updated as name list or name-value pairs. |
||
721 | * If the latter, the corresponding attribute values will be modified accordingly. |
||
722 | * The method will then save the specified attributes into database. |
||
723 | * |
||
724 | * Note that this method will **not** perform data validation and will **not** trigger events. |
||
725 | * |
||
726 | * @param array $attributes the attributes (names or name-value pairs) to be updated |
||
727 | * @return int the number of rows affected. |
||
728 | */ |
||
729 | 4 | public function updateAttributes($attributes) |
|
754 | |||
755 | /** |
||
756 | * @see update() |
||
757 | * @param array $attributes attributes to update |
||
758 | * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process. |
||
759 | * @throws StaleObjectException |
||
760 | */ |
||
761 | 21 | protected function updateInternal($attributes = null) |
|
798 | |||
799 | /** |
||
800 | * Updates one or several counter columns for the current AR object. |
||
801 | * Note that this method differs from [[updateAllCounters()]] in that it only |
||
802 | * saves counters for the current AR object. |
||
803 | * |
||
804 | * An example usage is as follows: |
||
805 | * |
||
806 | * ```php |
||
807 | * $post = Post::findOne($id); |
||
808 | * $post->updateCounters(['view_count' => 1]); |
||
809 | * ``` |
||
810 | * |
||
811 | * @param array $counters the counters to be updated (attribute name => increment value) |
||
812 | * Use negative values if you want to decrement the counters. |
||
813 | * @return bool whether the saving is successful |
||
814 | * @see updateAllCounters() |
||
815 | */ |
||
816 | 6 | public function updateCounters($counters) |
|
833 | |||
834 | /** |
||
835 | * Deletes the table row corresponding to this active record. |
||
836 | * |
||
837 | * This method performs the following steps in order: |
||
838 | * |
||
839 | * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the |
||
840 | * rest of the steps; |
||
841 | * 2. delete the record from the database; |
||
842 | * 3. call [[afterDelete()]]. |
||
843 | * |
||
844 | * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]] |
||
845 | * will be raised by the corresponding methods. |
||
846 | * |
||
847 | * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
||
848 | * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
||
849 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
850 | * being deleted is outdated. |
||
851 | * @throws Exception in case delete failed. |
||
852 | */ |
||
853 | public function delete() |
||
874 | |||
875 | /** |
||
876 | * Returns a value indicating whether the current record is new. |
||
877 | * @return bool whether the record is new and should be inserted when calling [[save()]]. |
||
878 | */ |
||
879 | 126 | public function getIsNewRecord() |
|
883 | |||
884 | /** |
||
885 | * Sets the value indicating whether the record is new. |
||
886 | * @param bool $value whether the record is new and should be inserted when calling [[save()]]. |
||
887 | * @see getIsNewRecord() |
||
888 | */ |
||
889 | public function setIsNewRecord($value) |
||
893 | |||
894 | /** |
||
895 | * Initializes the object. |
||
896 | * This method is called at the end of the constructor. |
||
897 | * The default implementation will trigger an [[EVENT_INIT]] event. |
||
898 | * If you override this method, make sure you call the parent implementation at the end |
||
899 | * to ensure triggering of the event. |
||
900 | */ |
||
901 | 349 | public function init() |
|
906 | |||
907 | /** |
||
908 | * This method is called when the AR object is created and populated with the query result. |
||
909 | * The default implementation will trigger an [[EVENT_AFTER_FIND]] event. |
||
910 | * When overriding this method, make sure you call the parent implementation to ensure the |
||
911 | * event is triggered. |
||
912 | */ |
||
913 | 250 | public function afterFind() |
|
917 | |||
918 | /** |
||
919 | * This method is called at the beginning of inserting or updating a record. |
||
920 | * |
||
921 | * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`, |
||
922 | * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`. |
||
923 | * When overriding this method, make sure you call the parent implementation like the following: |
||
924 | * |
||
925 | * ```php |
||
926 | * public function beforeSave($insert) |
||
927 | * { |
||
928 | * if (!parent::beforeSave($insert)) { |
||
929 | * return false; |
||
930 | * } |
||
931 | * |
||
932 | * // ...custom code here... |
||
933 | * return true; |
||
934 | * } |
||
935 | * ``` |
||
936 | * |
||
937 | * @param bool $insert whether this method called while inserting a record. |
||
938 | * If `false`, it means the method is called while updating a record. |
||
939 | * @return bool whether the insertion or updating should continue. |
||
940 | * If `false`, the insertion or updating will be cancelled. |
||
941 | */ |
||
942 | 100 | public function beforeSave($insert) |
|
949 | |||
950 | /** |
||
951 | * This method is called at the end of inserting or updating a record. |
||
952 | * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`, |
||
953 | * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]]. |
||
954 | * When overriding this method, make sure you call the parent implementation so that |
||
955 | * the event is triggered. |
||
956 | * @param bool $insert whether this method called while inserting a record. |
||
957 | * If `false`, it means the method is called while updating a record. |
||
958 | * @param array $changedAttributes The old values of attributes that had changed and were saved. |
||
959 | * You can use this parameter to take action based on the changes made for example send an email |
||
960 | * when the password had changed or implement audit trail that tracks all the changes. |
||
961 | * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has |
||
962 | * already the new, updated values. |
||
963 | * |
||
964 | * Note that no automatic type conversion performed by default. You may use |
||
965 | * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting. |
||
966 | * See http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting. |
||
967 | */ |
||
968 | 95 | public function afterSave($insert, $changedAttributes) |
|
974 | |||
975 | /** |
||
976 | * This method is invoked before deleting a record. |
||
977 | * |
||
978 | * The default implementation raises the [[EVENT_BEFORE_DELETE]] event. |
||
979 | * When overriding this method, make sure you call the parent implementation like the following: |
||
980 | * |
||
981 | * ```php |
||
982 | * public function beforeDelete() |
||
983 | * { |
||
984 | * if (!parent::beforeDelete()) { |
||
985 | * return false; |
||
986 | * } |
||
987 | * |
||
988 | * // ...custom code here... |
||
989 | * return true; |
||
990 | * } |
||
991 | * ``` |
||
992 | * |
||
993 | * @return bool whether the record should be deleted. Defaults to `true`. |
||
994 | */ |
||
995 | 6 | public function beforeDelete() |
|
1002 | |||
1003 | /** |
||
1004 | * This method is invoked after deleting a record. |
||
1005 | * The default implementation raises the [[EVENT_AFTER_DELETE]] event. |
||
1006 | * You may override this method to do postprocessing after the record is deleted. |
||
1007 | * Make sure you call the parent implementation so that the event is raised properly. |
||
1008 | */ |
||
1009 | 6 | public function afterDelete() |
|
1013 | |||
1014 | /** |
||
1015 | * Repopulates this active record with the latest data. |
||
1016 | * |
||
1017 | * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered. |
||
1018 | * This event is available since version 2.0.8. |
||
1019 | * |
||
1020 | * @return bool whether the row still exists in the database. If `true`, the latest data |
||
1021 | * will be populated to this active record. Otherwise, this record will remain unchanged. |
||
1022 | */ |
||
1023 | public function refresh() |
||
1029 | |||
1030 | /** |
||
1031 | * Repopulates this active record with the latest data from a newly fetched instance. |
||
1032 | * @param BaseActiveRecord $record the record to take attributes from. |
||
1033 | * @return bool whether refresh was successful. |
||
1034 | * @see refresh() |
||
1035 | * @since 2.0.13 |
||
1036 | */ |
||
1037 | protected function refreshInternal($record) |
||
1051 | |||
1052 | /** |
||
1053 | * This method is called when the AR object is refreshed. |
||
1054 | * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event. |
||
1055 | * When overriding this method, make sure you call the parent implementation to ensure the |
||
1056 | * event is triggered. |
||
1057 | * @since 2.0.8 |
||
1058 | */ |
||
1059 | public function afterRefresh() |
||
1063 | |||
1064 | /** |
||
1065 | * Returns a value indicating whether the given active record is the same as the current one. |
||
1066 | * The comparison is made by comparing the table names and the primary key values of the two active records. |
||
1067 | * If one of the records [[isNewRecord|is new]] they are also considered not equal. |
||
1068 | * @param ActiveRecordInterface $record record to compare to |
||
1069 | * @return bool whether the two active records refer to the same row in the same database table. |
||
1070 | */ |
||
1071 | public function equals($record) |
||
1079 | |||
1080 | /** |
||
1081 | * Returns the primary key value(s). |
||
1082 | * @param bool $asArray whether to return the primary key value as an array. If `true`, |
||
1083 | * the return value will be an array with column names as keys and column values as values. |
||
1084 | * Note that for composite primary keys, an array will always be returned regardless of this parameter value. |
||
1085 | * @property mixed The primary key value. An array (column name => column value) is returned if |
||
1086 | * the primary key is composite. A string is returned otherwise (null will be returned if |
||
1087 | * the key value is null). |
||
1088 | * @return mixed the primary key value. An array (column name => column value) is returned if the primary key |
||
1089 | * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if |
||
1090 | * the key value is null). |
||
1091 | */ |
||
1092 | 41 | public function getPrimaryKey($asArray = false) |
|
1106 | |||
1107 | /** |
||
1108 | * Returns the old primary key value(s). |
||
1109 | * This refers to the primary key value that is populated into the record |
||
1110 | * after executing a find method (e.g. find(), findOne()). |
||
1111 | * The value remains unchanged even if the primary key attribute is manually assigned with a different value. |
||
1112 | * @param bool $asArray whether to return the primary key value as an array. If `true`, |
||
1113 | * the return value will be an array with column name as key and column value as value. |
||
1114 | * If this is `false` (default), a scalar value will be returned for non-composite primary key. |
||
1115 | * @property mixed The old primary key value. An array (column name => column value) is |
||
1116 | * returned if the primary key is composite. A string is returned otherwise (null will be |
||
1117 | * returned if the key value is null). |
||
1118 | * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key |
||
1119 | * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if |
||
1120 | * the key value is null). |
||
1121 | * @throws Exception if the AR model does not have a primary key |
||
1122 | */ |
||
1123 | 47 | public function getOldPrimaryKey($asArray = false) |
|
1140 | |||
1141 | /** |
||
1142 | * Populates an active record object using a row of data from the database/storage. |
||
1143 | * |
||
1144 | * This is an internal method meant to be called to create active record objects after |
||
1145 | * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate |
||
1146 | * the query results into active records. |
||
1147 | * |
||
1148 | * When calling this method manually you should call [[afterFind()]] on the created |
||
1149 | * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]]. |
||
1150 | * |
||
1151 | * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance |
||
1152 | * created by [[instantiate()]] beforehand. |
||
1153 | * @param array $row attribute values (name => value) |
||
1154 | */ |
||
1155 | 250 | public static function populateRecord($record, $row) |
|
1167 | |||
1168 | /** |
||
1169 | * Creates an active record instance. |
||
1170 | * |
||
1171 | * This method is called together with [[populateRecord()]] by [[ActiveQuery]]. |
||
1172 | * It is not meant to be used for creating new records directly. |
||
1173 | * |
||
1174 | * You may override this method if the instance being created |
||
1175 | * depends on the row data to be populated into the record. |
||
1176 | * For example, by creating a record based on the value of a column, |
||
1177 | * you may implement the so-called single-table inheritance mapping. |
||
1178 | * @param array $row row data to be populated into the record. |
||
1179 | * @return static the newly created active record |
||
1180 | */ |
||
1181 | 244 | public static function instantiate($row) |
|
1185 | |||
1186 | /** |
||
1187 | * Returns whether there is an element at the specified offset. |
||
1188 | * This method is required by the interface [[\ArrayAccess]]. |
||
1189 | * @param mixed $offset the offset to check on |
||
1190 | * @return bool whether there is an element at the specified offset. |
||
1191 | */ |
||
1192 | 30 | public function offsetExists($offset) |
|
1196 | |||
1197 | /** |
||
1198 | * Returns the relation object with the specified name. |
||
1199 | * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object. |
||
1200 | * It can be declared in either the Active Record class itself or one of its behaviors. |
||
1201 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
1202 | * @param bool $throwException whether to throw exception if the relation does not exist. |
||
1203 | * @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist |
||
1204 | * and `$throwException` is `false`, `null` will be returned. |
||
1205 | * @throws InvalidParamException if the named relation does not exist. |
||
1206 | */ |
||
1207 | 132 | public function getRelation($name, $throwException = true) |
|
1243 | |||
1244 | /** |
||
1245 | * Establishes the relationship between two models. |
||
1246 | * |
||
1247 | * The relationship is established by setting the foreign key value(s) in one model |
||
1248 | * to be the corresponding primary key value(s) in the other model. |
||
1249 | * The model with the foreign key will be saved into database without performing validation. |
||
1250 | * |
||
1251 | * If the relationship involves a junction table, a new row will be inserted into the |
||
1252 | * junction table which contains the primary key values from both models. |
||
1253 | * |
||
1254 | * Note that this method requires that the primary key value is not null. |
||
1255 | * |
||
1256 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1257 | * @param ActiveRecordInterface $model the model to be linked with the current one. |
||
1258 | * @param array $extraColumns additional column values to be saved into the junction table. |
||
1259 | * This parameter is only meaningful for a relationship involving a junction table |
||
1260 | * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].) |
||
1261 | * @throws InvalidCallException if the method is unable to link two models. |
||
1262 | */ |
||
1263 | 9 | public function link($name, $model, $extraColumns = []) |
|
1340 | |||
1341 | /** |
||
1342 | * Destroys the relationship between two models. |
||
1343 | * |
||
1344 | * The model with the foreign key of the relationship will be deleted if `$delete` is `true`. |
||
1345 | * Otherwise, the foreign key will be set `null` and the model will be saved without validation. |
||
1346 | * |
||
1347 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1348 | * @param ActiveRecordInterface $model the model to be unlinked from the current one. |
||
1349 | * You have to make sure that the model is really related with the current model as this method |
||
1350 | * does not check this. |
||
1351 | * @param bool $delete whether to delete the model that contains the foreign key. |
||
1352 | * If `false`, the model's foreign key will be set `null` and saved. |
||
1353 | * If `true`, the model containing the foreign key will be deleted. |
||
1354 | * @throws InvalidCallException if the models cannot be unlinked |
||
1355 | */ |
||
1356 | 3 | public function unlink($name, $model, $delete = false) |
|
1439 | |||
1440 | /** |
||
1441 | * Destroys the relationship in current model. |
||
1442 | * |
||
1443 | * The model with the foreign key of the relationship will be deleted if `$delete` is `true`. |
||
1444 | * Otherwise, the foreign key will be set `null` and the model will be saved without validation. |
||
1445 | * |
||
1446 | * Note that to destroy the relationship without removing records make sure your keys can be set to null |
||
1447 | * |
||
1448 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1449 | * @param bool $delete whether to delete the model that contains the foreign key. |
||
1450 | * |
||
1451 | * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models. |
||
1452 | * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first |
||
1453 | * and then call [[delete()]] on each of them. |
||
1454 | */ |
||
1455 | 18 | public function unlinkAll($name, $delete = false) |
|
1528 | |||
1529 | /** |
||
1530 | * @param array $link |
||
1531 | * @param ActiveRecordInterface $foreignModel |
||
1532 | * @param ActiveRecordInterface $primaryModel |
||
1533 | * @throws InvalidCallException |
||
1534 | */ |
||
1535 | 9 | private function bindModels($link, $foreignModel, $primaryModel) |
|
1550 | |||
1551 | /** |
||
1552 | * Returns a value indicating whether the given set of attributes represents the primary key for this model. |
||
1553 | * @param array $keys the set of attributes to check |
||
1554 | * @return bool whether the given set of attributes represents the primary key for this model |
||
1555 | */ |
||
1556 | 15 | public static function isPrimaryKey($keys) |
|
1565 | |||
1566 | /** |
||
1567 | * Returns the text label for the specified attribute. |
||
1568 | * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model. |
||
1569 | * @param string $attribute the attribute name |
||
1570 | * @return string the attribute label |
||
1571 | * @see generateAttributeLabel() |
||
1572 | * @see attributeLabels() |
||
1573 | */ |
||
1574 | 51 | public function getAttributeLabel($attribute) |
|
1607 | |||
1608 | /** |
||
1609 | * Returns the text hint for the specified attribute. |
||
1610 | * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model. |
||
1611 | * @param string $attribute the attribute name |
||
1612 | * @return string the attribute hint |
||
1613 | * @see attributeHints() |
||
1614 | * @since 2.0.4 |
||
1615 | */ |
||
1616 | public function getAttributeHint($attribute) |
||
1649 | |||
1650 | /** |
||
1651 | * @inheritdoc |
||
1652 | * |
||
1653 | * The default implementation returns the names of the columns whose values have been populated into this record. |
||
1654 | */ |
||
1655 | public function fields() |
||
1661 | |||
1662 | /** |
||
1663 | * @inheritdoc |
||
1664 | * |
||
1665 | * The default implementation returns the names of the relations that have been populated into this record. |
||
1666 | */ |
||
1667 | public function extraFields() |
||
1673 | |||
1674 | /** |
||
1675 | * Sets the element value at the specified offset to null. |
||
1676 | * This method is required by the SPL interface [[\ArrayAccess]]. |
||
1677 | * It is implicitly called when you use something like `unset($model[$offset])`. |
||
1678 | * @param mixed $offset the offset to unset element |
||
1679 | */ |
||
1680 | 3 | public function offsetUnset($offset) |
|
1688 | } |
||
1689 |