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



每当我使用$model->attributes=$_POST['Users']时,它都会保存用户表单中的数据。

当我使用$model->setAttributes($_POST['Users'])时,它还保存用户表单中的数据

那么,有人能澄清一下这两个代码之间的区别吗?

使用$this->setAttributes()可以分配不安全的属性,而使用$this->attributes则不能。

分配不安全属性:

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

更多信息请访问:http://www.yiiframework.com/doc/api/1.1/CModel/#setAttributes-详细

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

绝对没有区别。

当您试图在组件上分配一个未定义为PHP类属性的属性(例如这里的attributes)时,Yii会按照约定调用类似名称的setter方法setAttributes。如果不存在这样的方法,则抛出异常。由于Yii模型是一个组件,并且模型没有attributes属性,因此即使使用第一种形式,也会调用setter方法。

所有这些在手册中也有详细的解释。

$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

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

最新更新