Ale*_*nko 4 behavior trim yii2
Yii2框架.为共同模型创建共同行为的想法:
如果它的数组修剪数组中的所有值.
我想知道为什么在Yii2核心中不存在这种可能性.或者我错了.我呢?
如果修剪所有字段,我可能遇到什么问题?
您可以创建行为并将其附加到模型中.
1)创建行为TrimBehavior在common/components.
<?php
namespace common\components;
use yii\db\ActiveRecord;
use yii\base\Behavior;
class TrimBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
];
}
public function beforeValidate($event)
{
$attributes = $this->owner->attributes;
foreach($attributes as $key => $value) { //For all model attributes
$this->owner->$key = trim($this->owner->$key);
}
}
}
Run Code Online (Sandbox Code Playgroud)
2)在您的模型中添加以下内容:
//...
use common\components\TrimBehavior;
//...
/**
* Returns a list of behaviors that this component should behave as.
*
* @return array
*/
public function behaviors()
{
return [
[
'class' => TrimBehavior::className(),
],
];
}
Run Code Online (Sandbox Code Playgroud)
修剪属性取决于业务逻辑.如果你真的需要它,那就没关系.