Complex classes like ActiveRecord 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 ActiveRecord, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
80 | class ActiveRecord extends BaseActiveRecord |
||
81 | { |
||
82 | /** |
||
83 | * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. |
||
84 | */ |
||
85 | const OP_INSERT = 0x01; |
||
86 | /** |
||
87 | * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. |
||
88 | */ |
||
89 | const OP_UPDATE = 0x02; |
||
90 | /** |
||
91 | * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. |
||
92 | */ |
||
93 | const OP_DELETE = 0x04; |
||
94 | /** |
||
95 | * All three operations: insert, update, delete. |
||
96 | * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE. |
||
97 | */ |
||
98 | const OP_ALL = 0x07; |
||
99 | |||
100 | |||
101 | /** |
||
102 | * Loads default values from database table schema. |
||
103 | * |
||
104 | * You may call this method to load default values after creating a new instance: |
||
105 | * |
||
106 | * ```php |
||
107 | * // class Customer extends \yii\db\ActiveRecord |
||
108 | * $customer = new Customer(); |
||
109 | * $customer->loadDefaultValues(); |
||
110 | * ``` |
||
111 | * |
||
112 | * @param bool $skipIfSet whether existing value should be preserved. |
||
113 | * This will only set defaults for attributes that are `null`. |
||
114 | * @return $this the model instance itself. |
||
115 | */ |
||
116 | 4 | public function loadDefaultValues($skipIfSet = true) |
|
126 | |||
127 | /** |
||
128 | * Returns the database connection used by this AR class. |
||
129 | * By default, the "db" application component is used as the database connection. |
||
130 | * You may override this method if you want to use a different database connection. |
||
131 | * @return Connection the database connection used by this AR class. |
||
132 | */ |
||
133 | 48 | public static function getDb() |
|
137 | |||
138 | /** |
||
139 | * Creates an [[ActiveQuery]] instance with a given SQL statement. |
||
140 | * |
||
141 | * Note that because the SQL statement is already specified, calling additional |
||
142 | * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]] |
||
143 | * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is |
||
144 | * still fine. |
||
145 | * |
||
146 | * Below is an example: |
||
147 | * |
||
148 | * ```php |
||
149 | * $customers = Customer::findBySql('SELECT * FROM customer')->all(); |
||
150 | * ``` |
||
151 | * |
||
152 | * @param string $sql the SQL statement to be executed |
||
153 | * @param array $params parameters to be bound to the SQL statement during execution. |
||
154 | * @return ActiveQuery the newly created [[ActiveQuery]] instance |
||
155 | */ |
||
156 | 6 | public static function findBySql($sql, $params = []) |
|
163 | |||
164 | /** |
||
165 | * Finds ActiveRecord instance(s) by the given condition. |
||
166 | * This method is internally called by [[findOne()]] and [[findAll()]]. |
||
167 | * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter |
||
168 | * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance. |
||
169 | * @throws InvalidConfigException if there is no primary key defined. |
||
170 | * @internal |
||
171 | */ |
||
172 | 217 | protected static function findByCondition($condition) |
|
195 | |||
196 | /** |
||
197 | * Filters array condition before it is assiged to a Query filter. |
||
198 | * |
||
199 | * This method will ensure that an array condition only filters on existing table columns. |
||
200 | * |
||
201 | * @param array $condition condition to filter. |
||
202 | * @return array filtered condition. |
||
203 | * @throws InvalidArgumentException in case array contains unsafe values. |
||
204 | * @since 2.0.15 |
||
205 | * @internal |
||
206 | */ |
||
207 | 68 | protected static function filterCondition(array $condition) |
|
231 | |||
232 | /** |
||
233 | * {@inheritdoc} |
||
234 | */ |
||
235 | 29 | public function refresh() |
|
250 | |||
251 | /** |
||
252 | * Updates the whole table using the provided attribute values and conditions. |
||
253 | * |
||
254 | * For example, to change the status to be 1 for all customers whose status is 2: |
||
255 | * |
||
256 | * ```php |
||
257 | * Customer::updateAll(['status' => 1], 'status = 2'); |
||
258 | * ``` |
||
259 | * |
||
260 | * > Warning: If you do not specify any condition, this method will update **all** rows in the table. |
||
261 | * |
||
262 | * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or |
||
263 | * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then |
||
264 | * call [[update()]] on each of them. For example an equivalent of the example above would be: |
||
265 | * |
||
266 | * ```php |
||
267 | * $models = Customer::find()->where('status = 2')->all(); |
||
268 | * foreach ($models as $model) { |
||
269 | * $model->status = 1; |
||
270 | * $model->update(false); // skipping validation as no user input is involved |
||
271 | * } |
||
272 | * ``` |
||
273 | * |
||
274 | * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits. |
||
275 | * |
||
276 | * @param array $attributes attribute values (name-value pairs) to be saved into the table |
||
277 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
278 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
279 | * @param array $params the parameters (name => value) to be bound to the query. |
||
280 | * @return int the number of rows updated |
||
281 | */ |
||
282 | 52 | public static function updateAll($attributes, $condition = '', $params = []) |
|
289 | |||
290 | /** |
||
291 | * Updates the whole table using the provided counter changes and conditions. |
||
292 | * |
||
293 | * For example, to increment all customers' age by 1, |
||
294 | * |
||
295 | * ```php |
||
296 | * Customer::updateAllCounters(['age' => 1]); |
||
297 | * ``` |
||
298 | * |
||
299 | * Note that this method will not trigger any events. |
||
300 | * |
||
301 | * @param array $counters the counters to be updated (attribute name => increment value). |
||
302 | * Use negative values if you want to decrement the counters. |
||
303 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
304 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
305 | * @param array $params the parameters (name => value) to be bound to the query. |
||
306 | * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method. |
||
307 | * @return int the number of rows updated |
||
308 | */ |
||
309 | 6 | public static function updateAllCounters($counters, $condition = '', $params = []) |
|
321 | |||
322 | /** |
||
323 | * Deletes rows in the table using the provided conditions. |
||
324 | * |
||
325 | * For example, to delete all customers whose status is 3: |
||
326 | * |
||
327 | * ```php |
||
328 | * Customer::deleteAll('status = 3'); |
||
329 | * ``` |
||
330 | * |
||
331 | * > Warning: If you do not specify any condition, this method will delete **all** rows in the table. |
||
332 | * |
||
333 | * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or |
||
334 | * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then |
||
335 | * call [[delete()]] on each of them. For example an equivalent of the example above would be: |
||
336 | * |
||
337 | * ```php |
||
338 | * $models = Customer::find()->where('status = 3')->all(); |
||
339 | * foreach ($models as $model) { |
||
340 | * $model->delete(); |
||
341 | * } |
||
342 | * ``` |
||
343 | * |
||
344 | * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits. |
||
345 | * |
||
346 | * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL. |
||
347 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
348 | * @param array $params the parameters (name => value) to be bound to the query. |
||
349 | * @return int the number of rows deleted |
||
350 | */ |
||
351 | 32 | public static function deleteAll($condition = null, $params = []) |
|
358 | |||
359 | /** |
||
360 | * {@inheritdoc} |
||
361 | * @return ActiveQuery the newly created [[ActiveQuery]] instance. |
||
362 | */ |
||
363 | 314 | public static function find() |
|
367 | |||
368 | /** |
||
369 | * Declares the name of the database table associated with this AR class. |
||
370 | * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]] |
||
371 | * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`, |
||
372 | * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method |
||
373 | * if the table is not named after this convention. |
||
374 | * @return string the table name |
||
375 | */ |
||
376 | 15 | public static function tableName() |
|
380 | |||
381 | /** |
||
382 | * Returns the schema information of the DB table associated with this AR class. |
||
383 | * @return TableSchema the schema information of the DB table associated with this AR class. |
||
384 | * @throws InvalidConfigException if the table for the AR class does not exist. |
||
385 | */ |
||
386 | 450 | public static function getTableSchema() |
|
398 | |||
399 | /** |
||
400 | * Returns the primary key name(s) for this AR class. |
||
401 | * The default implementation will return the primary key(s) as declared |
||
402 | * in the DB table that is associated with this AR class. |
||
403 | * |
||
404 | * If the DB table does not declare any primary key, you should override |
||
405 | * this method to return the attributes that you want to use as primary keys |
||
406 | * for this AR class. |
||
407 | * |
||
408 | * Note that an array should be returned even for a table with single primary key. |
||
409 | * |
||
410 | * @return string[] the primary keys of the associated database table. |
||
411 | */ |
||
412 | 257 | public static function primaryKey() |
|
416 | |||
417 | /** |
||
418 | * Returns the list of all attribute names of the model. |
||
419 | * The default implementation will return all column names of the table associated with this AR class. |
||
420 | * @return array list of attribute names. |
||
421 | */ |
||
422 | 420 | public function attributes() |
|
426 | |||
427 | /** |
||
428 | * Declares which DB operations should be performed within a transaction in different scenarios. |
||
429 | * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]], |
||
430 | * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively. |
||
431 | * By default, these methods are NOT enclosed in a DB transaction. |
||
432 | * |
||
433 | * In some scenarios, to ensure data consistency, you may want to enclose some or all of them |
||
434 | * in transactions. You can do so by overriding this method and returning the operations |
||
435 | * that need to be transactional. For example, |
||
436 | * |
||
437 | * ```php |
||
438 | * return [ |
||
439 | * 'admin' => self::OP_INSERT, |
||
440 | * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE, |
||
441 | * // the above is equivalent to the following: |
||
442 | * // 'api' => self::OP_ALL, |
||
443 | * |
||
444 | * ]; |
||
445 | * ``` |
||
446 | * |
||
447 | * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]]) |
||
448 | * should be done in a transaction; and in the "api" scenario, all the operations should be done |
||
449 | * in a transaction. |
||
450 | * |
||
451 | * @return array the declarations of transactional operations. The array keys are scenarios names, |
||
452 | * and the array values are the corresponding transaction operations. |
||
453 | */ |
||
454 | 114 | public function transactions() |
|
458 | |||
459 | /** |
||
460 | * {@inheritdoc} |
||
461 | */ |
||
462 | 328 | public static function populateRecord($record, $row) |
|
472 | |||
473 | /** |
||
474 | * Inserts a row into the associated database table using the attribute values of this record. |
||
475 | * |
||
476 | * This method performs the following steps in order: |
||
477 | * |
||
478 | * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]] |
||
479 | * returns `false`, the rest of the steps will be skipped; |
||
480 | * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation |
||
481 | * failed, the rest of the steps will be skipped; |
||
482 | * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`, |
||
483 | * the rest of the steps will be skipped; |
||
484 | * 4. insert the record into database. If this fails, it will skip the rest of the steps; |
||
485 | * 5. call [[afterSave()]]; |
||
486 | * |
||
487 | * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]], |
||
488 | * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]] |
||
489 | * will be raised by the corresponding methods. |
||
490 | * |
||
491 | * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database. |
||
492 | * |
||
493 | * If the table's primary key is auto-incremental and is `null` during insertion, |
||
494 | * it will be populated with the actual value after insertion. |
||
495 | * |
||
496 | * For example, to insert a customer record: |
||
497 | * |
||
498 | * ```php |
||
499 | * $customer = new Customer; |
||
500 | * $customer->name = $name; |
||
501 | * $customer->email = $email; |
||
502 | * $customer->insert(); |
||
503 | * ``` |
||
504 | * |
||
505 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
506 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
507 | * will not be saved to the database and this method will return `false`. |
||
508 | * @param array $attributes list of attributes that need to be saved. Defaults to `null`, |
||
509 | * meaning all attributes that are loaded from DB will be saved. |
||
510 | * @return bool whether the attributes are valid and the record is inserted successfully. |
||
511 | * @throws \Exception|\Throwable in case insert failed. |
||
512 | */ |
||
513 | 98 | public function insert($runValidation = true, $attributes = null) |
|
542 | |||
543 | /** |
||
544 | * Inserts an ActiveRecord into DB without considering transaction. |
||
545 | * @param array $attributes list of attributes that need to be saved. Defaults to `null`, |
||
546 | * meaning all attributes that are loaded from DB will be saved. |
||
547 | * @return bool whether the record is inserted successfully. |
||
548 | */ |
||
549 | 98 | protected function insertInternal($attributes = null) |
|
570 | |||
571 | /** |
||
572 | * Saves the changes to this active record into the associated database table. |
||
573 | * |
||
574 | * This method performs the following steps in order: |
||
575 | * |
||
576 | * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]] |
||
577 | * returns `false`, the rest of the steps will be skipped; |
||
578 | * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation |
||
579 | * failed, the rest of the steps will be skipped; |
||
580 | * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`, |
||
581 | * the rest of the steps will be skipped; |
||
582 | * 4. save the record into database. If this fails, it will skip the rest of the steps; |
||
583 | * 5. call [[afterSave()]]; |
||
584 | * |
||
585 | * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]], |
||
586 | * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]] |
||
587 | * will be raised by the corresponding methods. |
||
588 | * |
||
589 | * Only the [[dirtyAttributes|changed attribute values]] will be saved into database. |
||
590 | * |
||
591 | * For example, to update a customer record: |
||
592 | * |
||
593 | * ```php |
||
594 | * $customer = Customer::findOne($id); |
||
595 | * $customer->name = $name; |
||
596 | * $customer->email = $email; |
||
597 | * $customer->update(); |
||
598 | * ``` |
||
599 | * |
||
600 | * Note that it is possible the update does not affect any row in the table. |
||
601 | * In this case, this method will return 0. For this reason, you should use the following |
||
602 | * code to check if update() is successful or not: |
||
603 | * |
||
604 | * ```php |
||
605 | * if ($customer->update() !== false) { |
||
606 | * // update successful |
||
607 | * } else { |
||
608 | * // update failed |
||
609 | * } |
||
610 | * ``` |
||
611 | * |
||
612 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
613 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
614 | * will not be saved to the database and this method will return `false`. |
||
615 | * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`, |
||
616 | * meaning all attributes that are loaded from DB will be saved. |
||
617 | * @return int|false the number of rows affected, or false if validation fails |
||
618 | * or [[beforeSave()]] stops the updating process. |
||
619 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
620 | * being updated is outdated. |
||
621 | * @throws \Exception|\Throwable in case update failed. |
||
622 | */ |
||
623 | 40 | public function update($runValidation = true, $attributeNames = null) |
|
652 | |||
653 | /** |
||
654 | * Deletes the table row corresponding to this active record. |
||
655 | * |
||
656 | * This method performs the following steps in order: |
||
657 | * |
||
658 | * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the |
||
659 | * rest of the steps; |
||
660 | * 2. delete the record from the database; |
||
661 | * 3. call [[afterDelete()]]. |
||
662 | * |
||
663 | * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]] |
||
664 | * will be raised by the corresponding methods. |
||
665 | * |
||
666 | * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
||
667 | * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
||
668 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
669 | * being deleted is outdated. |
||
670 | * @throws \Exception|\Throwable in case delete failed. |
||
671 | */ |
||
672 | 7 | public function delete() |
|
696 | |||
697 | /** |
||
698 | * Deletes an ActiveRecord without considering transaction. |
||
699 | * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
||
700 | * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
||
701 | * @throws StaleObjectException |
||
702 | */ |
||
703 | 7 | protected function deleteInternal() |
|
725 | |||
726 | /** |
||
727 | * Returns a value indicating whether the given active record is the same as the current one. |
||
728 | * The comparison is made by comparing the table names and the primary key values of the two active records. |
||
729 | * If one of the records [[isNewRecord|is new]] they are also considered not equal. |
||
730 | * @param ActiveRecord $record record to compare to |
||
731 | * @return bool whether the two active records refer to the same row in the same database table. |
||
732 | */ |
||
733 | 3 | public function equals($record) |
|
741 | |||
742 | /** |
||
743 | * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]]. |
||
744 | * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]]. |
||
745 | * @return bool whether the specified operation is transactional in the current [[scenario]]. |
||
746 | */ |
||
747 | 114 | public function isTransactional($operation) |
|
754 | } |
||
755 |
This check looks at variables that have been passed in as parameters and are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.