yii2源码学习笔记(七)

Posted dragon16

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2源码学习笔记(七)相关的知识,希望对你有一定的参考价值。

今天继续了解model类

  1   1   /**
  2   2      * Returns the form name that this model class should use.
  3   3      *
  4   4      * 返回表单的名称,就是这个 model 的类名
  5   5      *
  6   6      * The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name
  7   7      * the input fields for the attributes in a model. If the form name is "A" and an attribute
  8   8      * name is "b", then the corresponding input name would be "A[b]". If the form name is
  9   9      * an empty string, then the input name would be "b".
 10  10      *
 11  11      * By default, this method returns the model class name (without the namespace part)
 12  12      * as the form name. You may override it when the model is used in different forms.
 13  13      *
 14  14      * @return string the form name of this model class.
 15  15      */
 16  16     public function formName()
 17  17     {
 18  18         // ReflectionClass 类包含了一个类的有关信息
 19  19         $reflector = new ReflectionClass($this);
 20  20         // 获取类的短名,就是不含命名空间(namespace)的那一部分
 21  21         return $reflector->getShortName();
 22  22     }
 23  23 
 24  24     /**
 25  25      * Returns the list of attribute names.
 26  26      * 返回属性名的列表,注意:只会返回 public 且不是 static 的属性
 27  27      * By default, this method returns all public non-static properties of the class.
 28  28      * You may override this method to change the default behavior.
 29  29      * @return array list of attribute names.
 30  30      */
 31  31     public function attributes()
 32  32     {
 33  33         $class = new ReflectionClass($this);
 34  34         $names = [];
 35  35         // ReflectionClass::getProperties — 获取一组属性
 36  36         // ReflectionProperty::IS_STATIC 指示了 static 的属性。
 37  37         // ReflectionProperty::IS_PUBLIC 指示了 public 的属性。
 38  38         // ReflectionProperty::IS_PROTECTED 指示了 protected 的属性。
 39  39         // ReflectionProperty::IS_PRIVATE 指示了 private 的属性。
 40  40         foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
 41  41             // 如果是public的属性,并且不是static的,就认为是它的attribute
 42  42             if (!$property->isStatic()) {
 43  43                 // 获取该属性的名称
 44  44                 $names[] = $property->getName();
 45  45             }
 46  46         }
 47  47 
 48  48         return $names;
 49  49     }
 50  50 
 51  51     /**
 52  52      * Returns the attribute labels.
 53  53      * 返回属性的标签
 54  54      *
 55  55      * Attribute labels are mainly used for display purpose. For example, given an attribute
 56  56      * `firstName`, we can declare a label `First Name` which is more user-friendly and can
 57  57      * be displayed to end users.
 58  58      *
 59  59      * By default an attribute label is generated using [[generateAttributeLabel()]].
 60  60      * This method allows you to explicitly specify attribute labels.
 61  61      *
 62  62      * Note, in order to inherit labels defined in the parent class, a child class needs to
 63  63      * merge the parent labels with child labels using functions such as `array_merge()`.
 64  64      *
 65  65      * @return array attribute labels (name => label)
 66  66      * @see generateAttributeLabel()
 67  67      */
 68  68     public function attributeLabels()
 69  69     {
 70  70         return [];
 71  71     }
 72  72 
 73  73     /**
 74  74      * Performs the data validation.
 75  75      *
 76  76      * This method executes the validation rules applicable to the current [[scenario]].
 77  77      * The following criteria are used to determine whether a rule is currently applicable:
 78  78      *
 79  79      * - the rule must be associated with the attributes relevant to the current scenario;
 80  80      * - the rules must be effective for the current scenario.
 81  81      *
 82  82      * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
 83  83      * after the actual validation, respectively. If [[beforeValidate()]] returns false,
 84  84      * the validation will be cancelled and [[afterValidate()]] will not be called.
 85  85      *
 86  86      * Errors found during the validation can be retrieved via [[getErrors()]],
 87  87      * [[getFirstErrors()]] and [[getFirstError()]].
 88  88      *
 89  89      * @param array $attributeNames list of attribute names that should be validated.
 90  90      * If this parameter is empty, it means any attribute listed in the applicable
 91  91      * validation rules should be validated.
 92  92      * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
 93  93      * @return boolean whether the validation is successful without any error.
 94  94      * @throws InvalidParamException if the current scenario is unknown.
 95  95      */
 96  96     public function validate($attributeNames = null, $clearErrors = true)
 97  97     {
 98  98         if ($clearErrors) {
 99  99             $this->clearErrors();
100 100         }
101 101 
102 102         if (!$this->beforeValidate()) {
103 103             return false;
104 104         }
105 105 
106 106         $scenarios = $this->scenarios();
107 107         $scenario = $this->getScenario();
108 108         if (!isset($scenarios[$scenario])) {
109 109             throw new InvalidParamException("Unknown scenario: $scenario");
110 110         }
111 111 
112 112         if ($attributeNames === null) {
113 113             $attributeNames = $this->activeAttributes();
114 114         }
115 115 
116 116         foreach ($this->getActiveValidators() as $validator) {
117 117             $validator->validateAttributes($this, $attributeNames);
118 118         }
119 119         $this->afterValidate();
120 120 
121 121         return !$this->hasErrors();
122 122     }
123 123 
124 124     /**
125 125      * This method is invoked before validation starts.
126 126      * The default implementation raises a `beforeValidate` event.
127 127      * You may override this method to do preliminary checks before validation.
128 128      * Make sure the parent implementation is invoked so that the event can be raised.
129 129      * @return boolean whether the validation should be executed. Defaults to true.
130 130      * If false is returned, the validation will stop and the model is considered invalid.
131 131      */
132 132     public function beforeValidate()
133 133     {
134 134         $event = new ModelEvent;
135 135         $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
136 136 
137 137         return $event->isValid;
138 138     }
139 139 
140 140     /**
141 141      * This method is invoked after validation ends.
142 142      * The default implementation raises an `afterValidate` event.
143 143      * You may override this method to do postprocessing after validation.
144 144      * Make sure the parent implementation is invoked so that the event can be raised.
145 145      */
146 146     public function afterValidate()
147 147     {
148 148         $this->trigger(self::EVENT_AFTER_VALIDATE);
149 149     }
150 150 
151 151     /**
152 152      * Returns all the validators declared in [[rules()]].
153 153      *
154 154      * This method differs from [[getActiveValidators()]] in that the latter
155 155      * only returns the validators applicable to the current [[scenario]].
156 156      *
157 157      * Because this method returns an ArrayObject object, you may
158 158      * manipulate it by inserting or removing validators (useful in model behaviors).
159 159      * For example,
160 160      *
161 161      * ~~~
162 162      * $model->validators[] = $newValidator;
163 163      * ~~~
164 164      *
165 165      * @return ArrayObject|\yii\validators\Validator[] all the validators declared in the model.
166 166      */
167 167     public function getValidators()
168 168     {
169 169         if ($this->_validators === null) {
170 170             $this->_validators = $this->createValidators();
171 171         }
172 172         return $this->_validators;
173 173     }
174 174 
175 175     /**
176 176      * Returns the validators applicable to the current [[scenario]].
177 177      * @param string $attribute the name of the attribute whose applicable validators should be returned.
178 178      * If this is null, the validators for ALL attributes in the model will be returned.
179 179      * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
180 180      */
181 181     public function getActiveValidators($attribute = null)
182 182     {
183 183         $validators = [];
184 184         $scenario = $this->getScenario();
185 185         foreach ($this->getValidators() as $validator) {
186 186             if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->attributes, true))) {
187 187                 $validators[] = $validator;
188 188             }
189 189         }
190 190         return $validators;
191 191     }
192 192 
193 193     /**
194 194      * Creates validator objects based on the validation rules specified in [[rules()]].
195 195      * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
196 196      * @return ArrayObject validators
197 197      * @throws InvalidConfigException if any validation rule configuration is invalid
198 198      */
199 199     public function createValidators()
200 200     {
201 201         $validators = new ArrayObject;
202 202         foreach ($this->rules() as $rule) {
203 203             if ($rule instanceof Validator) {
204 204                 $validators->append($rule);
205 205             } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
206 206                 $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
207 207                 $validators->append($validator);
208 208             } else {
209 209                 throw new InvalidConfigException(Invalid validation rule: a rule must specify both attribute names and validator type.);
210 210             }
211 211         }
212 212         return $validators;
213 213     }
214 214 
215 215     /**
216 216      * Returns a value indicating whether the attribute is required.
217 217      * This is determined by checking if the attribute is associated with a
218 218      * [[\yii\validators\RequiredValidator|required]] validation rule in the
219 219      * current [[scenario]].
220 220      *
221 221      * Note that when the validator has a conditional validation applied using
222 222      * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
223 223      * `false` regardless of the `when` condition because it may be called be
224 224      * before the model is loaded with data.
225 225      *
226 226      * @param string $attribute attribute name
227 227      * @return boolean whether the attribute is required
228 228      */
229 229     public function isAttributeRequired($attribute)
230 230     {
231 231         foreach ($this->getActiveValidators($attribute) as $validator) {
232 232             if ($validator instanceof RequiredValidator && $validator->when === null) {
233 233                 return true;
234 234             }
235 235         }
236 236         return false;
237 237     }
238 238 
239 239     /**
240 240      * Returns a value indicating whether the attribute is safe for massive assignments.
241 241      * @param string $attribute attribute name
242 242      * @return boolean whether the attribute is safe for massive assignments
243 243      * @see safeAttributes()
244 244      */
245 245     public function isAttributeSafe($attribute)
246 246     {
247 247         return in_array($attribute, $this->safeAttributes(), true);
248 248     }
249 249 
250 250     /**
251 251      * Returns a value indicating whether the attribute is active in the current scenario.
252 252      * @param string $attribute attribute name
253 253      * @return boolean whether the attribute is active in the current scenario
254 254      * @see activeAttributes()
255 255      */
256 256     public function isAttributeActive($attribute)
257 257     {
258 258         return in_array($attribute, $this->activeAttributes(), true);
259 259     }
260 260 
261 261     /**
262 262      * Returns the text label for the specified attribute.
263 263      * @param string $attribute the attribute name
264 264      * @return string the attribute label
265 265      * @see generateAttributeLabel()
266 266      * @see attributeLabels()
267 267      */
268 268     public function getAttributeLabel($attribute)
269 269     {
270 270         $labels = $this->attributeLabels();
271 271         return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
272 272     }
273 273 
274 274     /**
275 275      * Returns a value indicating whether there is any validation error.
276 276      * @param string|null $attribute attribute name. Use null to check all attributes.
277 277      * @return boolean whether there is any error.
278 278      */
279 279     public function hasErrors($attribute = null)
280 280     {
281 281         return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
282 282     }
283 283 
284 284     /**
285 285      * Returns the errors for all attribute or a single attribute.
286 286      * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
287 287      * @property array An array of errors for all attributes. Empty array is returned if no error.
288 288      * The result is a two-dimensional array. See [[getErrors()]] for detailed description.
289 289      * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
290 290      * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
291 291      *
292 292      * ~~~
293 293      * [
294 294      *     ‘username‘ => [
295 295      *         ‘Username is required.‘,
296 296      *         ‘Username must contain only word characters.‘,
297 297      *     ],
298 298      *     ‘email‘ => [
299 299      *         ‘Email address is invalid.‘,
300 300      *     ]
301 301      * ]
302 302      * ~~~
303 303      *
304 304      * @see getFirstErrors()
305 305      * @see getFirstError()
306 306      */
307 307     public function getErrors($attribute = null)
308 308     {
309 309         if ($attribute === null) {
310 310             return $this->_errors === null ? [] : $this->_errors;
311 311         } else {
312 312             return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
313 313         }
314 314     }
315 315 
316 316     /**
317 317      * Returns the first error of every attribute in the model.
318 318      * @return array the first errors. The array keys are the attribute names, and the array
319 319      * values are the corresponding error messages. An empty array will be returned if there is no error.
320 320      * @see getErrors()
321 321      * @see getFirstError()
322 322      */
323 323     public function getFirstErrors()
324 324     {
325 325         if (empty($this->_errors)) {
326 326             return [];
327 327         } else {
328 328             $errors = [];
329 329             foreach ($this->_errors as $name => $es) {
330 330                 if (!empty($es)) {
331 331                     $errors[$name] = reset($es);
332 332                 }
333 333             }
334 334 
335 335             return $errors;
336 336         }
337 337     }
338 338 
339 339     /**
340 340      * Returns the first error of the specified attribute.
341 341      * @param string $attribute attribute name.
342 342      * @return string the error message. Null is returned if no error.
343 343      * @see getErrors()
344 344      * @see getFirstErrors()
345 345      */
346 346     public function getFirstError($attribute)
347 347     {
348 348         return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
349 349     }
350 350 
351 351     /**
352 352      * Adds a new error to the specified attribute.
353 353      * @param string $attribute attribute name
354 354      * @param string $error new error message
355 355      */
356 356     public function addError($attribute, $error = ‘‘)
357 357     {
358 358         $this->_errors[$attribute][] = $error;
359 359     }
360 360 
361 361     /**
362 362      * Adds a list of errors.
363 363      * @param array $items a list of errors. The array keys must be attribute names.
364 364      * The array values should be error messages. If an attribute has multiple errors,
365 365      * these errors must be given in terms of an array.
366 366      * You may use the result of [[getErrors()]] as the value for this parameter.
367 367      * @since 2.0.2
368 368      */
369 369     public function addErrors(array $items)
370 370     {
371 371         foreach ($items as $attribute => $errors) {
372 372             if (is_array($errors)) {
373 373                 foreach ($errors as $error) {
374 374                     $this->addError($attribute, $error);
375 375                 }
376 376             } else {
377 377                 $this->addError($attribute, $errors);
378 378             }
379 379         }
380 380     }
381 381 
382 382     /**
383 383      * Removes errors for all attributes or a single attribute.
384 384      * @param string $attribute attribute name. Use null to remove errors for all attribute.
385 385      */
386 386     public function clearErrors($attribute = null)
387 387     {
388 388         if ($attribute === null) {
389 389             $this->_errors = [];
390 390         } else {
391 391             unset($this->_errors[$attribute]);
392 392         }
393 393     }
394 394 
395 395     /**
396 396      * Generates a user friendly attribute label based on the give attribute name.
397 397      * This is done by replacing underscores, dashes and dots with blanks and
398 398      * changing the first letter of each word to upper case.
399 399      * For example, ‘department_name‘ or ‘DepartmentName‘ will generate ‘Department Name‘.
400 400      * @param string $name the column name
401 401      * @return string the attribute label
402 402      */
403 403     public function generateAttributeLabel($name)
404 404     {
405 405         return Inflector::camel2words($name, true);
406 406     }
407 407 
408 408     /**
409 409      * Returns attribute values.
410 410      * @param array $names list of attributes whose value needs to be returned.
411 411      * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
412 412      * If it is an array, only the attributes in the array will be returned.
413 413      * @param array $except list of attributes whose value should NOT be returned.
414 414      * @return

以上是关于yii2源码学习笔记(七)的主要内容,如果未能解决你的问题,请参考以下文章

yii2源码学习笔记(三)

yii2源码学习笔记(十九)

yii2源码学习笔记(十六)

yii2源码学习笔记(四)

yii2源码学习笔记(六)

yii2源码学习笔记(五)