我這里用的數據庫是mongo 數據庫 為栗子:
public function load($data, $formName = null) { $scope = $formName === null ? $this->formName() : $formName; //調用load 一般我是 $test = new test() $test->load('參數1','參數2')
// 參數1 一般是post get 傳過來的參數 第二個參數 是一個空字符串 '';
// $this->formName() 返回的額是 你實例化的類的名字 new test() 最后返回的是test
if ($scope === '' && !empty($data)) { $this->setAttributes($data); //進入 return true; } elseif (isset($data[$scope])) { $this->setAttributes($data[$scope]); return true; } else { return false; } }
接下來看 setAttributes()
public function setAttributes($values, $safeOnly = true) { if (is_array($values)) { $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
//這里執行的是$this->safeAttributes()方法,該方法返回的是當前場景下需要驗證的字段。最后$attributes打印下來看下圖
foreach ($values as $name => $value) {
if (isset($attributes[$name])) {
$this->$name = $value;
} elseif ($safeOnly) {
$this->onUnsafeAttribute($name, $value);
} }
}
}
圖: 圖1的文件名是test 實例化后是$test 對象 public function attribues() 方法中對應的就是表字段。
我這里沒有用場景 所以暫時不講解場景這個功能。 不過大家可以看手冊。很容易懂。
這兩個圖是對相應的
在之后 執行的是 foreache循環 這里的$this 是那個$test 這個對象對象去調用
//例如post 提交過來的數據是這樣
$post=[
'a'=>123456,
'b'=>'abcdef'
]
$test->a=123456
$test->b='abcdef'
所以這個load()方法只是分配post 或者get 發過來的數據,不做驗證。
接下來看save();
查看save方法 。
public function save($runValidation = true, $attributeNames = null) { if ($this->getIsNewRecord()) { //判斷是否是新紀錄 return $this->insert($runValidation, $attributeNames); //執行這里 之后$this代表的是test 這個模型表。
//test 繼承的是\yii\mongodb\ActiveRecord 查看insert() 方法 。
} else {
return $this->update($runValidation, $attributeNames) !== false; }
}
insert() 方法中
public function insert($runValidation = true, $attributes = null) { if ($runValidation && !$this->validate($attributes)) { //下面的代碼分析validate方法 驗證rules return false; } $result = $this->insertInternal($attributes); //保存數據 return $result; }
首先看
//進行數據驗證。
public function validate($attributeNames = null, $clearErrors = true) { if ($clearErrors) { $this->clearErrors(); } if (!$this->beforeValidate()) { //在驗證之前首先執行的是 beforValidata return false; } $scenarios = $this->scenarios(); $scenario = $this->getScenario(); //檢查是否調用場景 if (!isset($scenarios[$scenario])) { throw new InvalidParamException("Unknown scenario: $scenario"); } if ($attributeNames === null) { $attributeNames = $this->activeAttributes(); //返回數組(值為屬性的名稱) } //$this->getActiveValidators() 驗證數據。 讀取rules 方法 getActiveValidators() ->getValidators()->createValidators()這里驗證rules等信息->createValidator()
foreach ($this->getActiveValidators() as $validator) {
$validator->validateAttributes($this, $attributeNames); //獲取交集 檢查是否有錯誤 hasError()
}
$this->afterValidate();
return !$this->hasErrors(); }
此時數據驗證完畢,之后就保存數據 保存數據這塊 就暫時不寫了 后續補上。
好了 其中數據驗證那一塊 大家多看看源碼吧。 一遍不行2遍 3遍 多了就懂了。
小弟先總結到這里了