Yii中的$ model-> attributes和$ model-> setAttributes()之间的区别

Yii中的$ model-> attributes和$ model-> setAttributes()之间的区别

问题描述:

每当我使用$model->attributes=$_POST['Users']时,它都会保存来自User窗体的数据。

当我使用$model->setAttributes($_POST['Users'])时,它也保存来自用户窗体的数据。

那么请谁能澄清两个代码之间的区别?

+0

我只是猜测,但'setAttributes()'还应该运行一些验证规则。 – Narf 2014-09-02 13:13:37

如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方法。

绝对没有区别。

当您尝试分配未在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

$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

随着$this->setAttributes()可以分配不安全属性,使用$this->attributes你不能。

分配不安全属性:在

$this->setAttributes($_POST['Model'], false); 

更多信息:http://www.yiiframework.com/doc/api/1.1/CModel/#setAttributes-detail

+0

我很满意你的回答@Marcos。 – 2014-09-03 04:58:07

没有区别。 array_merge用于合并属性,如果以后设置