2014-09-02 31 views
2

每當我使用$model->attributes=$_POST['Users']時,它都會保存來自User窗體的數據。

當我使用$model->setAttributes($_POST['Users'])時,它也保存來自用戶窗體的數據。

那麼請誰能澄清兩個代碼之間的區別?

+0

我只是猜測,但'setAttributes()'還應該運行一些驗證規則。 – Narf 2014-09-02 13:13:37

回答

1

如Yii wiki所述,您可以使用其中任何一種。用$model->attributes可以直接設置變量。通過$model->setAttributes(),您可以通過所謂的「setter方法」來設置變量。

http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/#hh1

我會使用setter方法,而不是直接調用的變量,你可以在你的setter方法添加一條線,這將適用於所有的呼叫,它會幫你逃脫很多頭痛在未來。

例子:

class Model { 
    public $attributes; 

    public function setAttributes($attributes) { 
    $this->attributes = $attributes; 
    } 
    public function getAttributes() { 
    return $this->attributes; 
    } 
} 

$model = new Model(); 
$model->setAttributes("Foo"); 
echo $model->getAttributes(); 
$model->setAttributes("Bar"); 
echo $model->getAttributes(); 

所以,現在如果你想使對屬性的附加操作,你可以將它添加到setAttributes()方法,而不是改變兩行代碼,你可以改變只有一個。

例子:

class Model { 
    public $attributes; 

    public function setAttributes($attributes) { 
    $this->attributes = $attributes . "-Bar"; 
    } 
    public function getAttributes() { 
    return $this->attributes; 
    } 
} 

$model = new Model(); 
$model->setAttributes("Foo"); 
echo $model->getAttributes(); 
$model->setAttributes("Bar"); 
echo $model->getAttributes(); 

現在這個規模達的水平,當它會帶來不便更改數千行代碼,而不是改變一對夫婦的setter方法。

2

絕對沒有區別。

當您嘗試分配未在component定義爲PHP類屬性(如attributes這裏)的屬性,通過Yii中調用約定的類似名稱的setter方法setAttributes代替。如果不存在這樣的方法,則拋出異常。由於Yii模型是一個組件,並且模型沒有attributes屬性,因此即使在使用第一個窗體時也會調用setter方法。

本手冊中所有這些也都是explained in detail

+1

請確認您的回答中包含必要的鏈接部分,因爲鏈接已知會在一段時間內死亡。 – 2014-09-02 13:23:33

+0

@CaffeineCoder:我想我已經做到了。 – Jon 2014-09-02 13:25:35

+0

我指的是那裏提到的例子。 – 2014-09-02 13:27:46

1
$model->attributes=$_POST['Users']// means setting value of property directly while 
$model->setAttributes($_POST['Users']) //is method or function which is indirectly set value of $model->attributes property; 

讓我們舉一個例子

class Model{ 
     public $attributes; 


     public function setAttributes($att){ 
      $this->attributes=$att; 

     } 


    } 

      //Now the value of $attributes can be set by two way 


$model = new Model(); 
$model->attributes=$value; // 1st way 
$model->setAttributes($value); //2nd way 
+1

這個例子是完全錯誤的,錯過了這一點。 Yii模型繼承了使它們以不同方式工作的代碼。沒有'$ attributes'屬性。 – Jon 2014-09-02 13:18:57

+0

這不是Yii。其OPP PHP和示例的一般概念並不是Yii代碼的唯一一般示例 – Vicky 2014-09-02 13:21:06

+1

但是問題是關於Yii的,這就是爲什麼忽略了這一點。 – Jon 2014-09-02 13:21:52

0

沒有區別。 array_merge用於合併屬性,如果以後設置