如何删除 Yii2 验证器方法 `when` 中的代码重复?

How to remove code repetition in Yii2 validators method `when`?

你必须阅读我之前的问题才能理解我在这里谈论的内容()。于是就解决了。

但是我的视图中有很多字段总是由当前用户的值填充。当我做下一步时它是代码重复

[['new_email'], 'unique', 'targetAttribute' => 'email', 'targetClass' => '\common\models\User',
            'when' => function ($model, $attribute) {
                $this->isNewEmail = false;
                if($model->$attribute != User::find()->where(['id' => Yii::$app->user->id])->one()->email) {
                    $this->isNewEmail = true;
                }
                return $this->isNewEmail;
            },
            'message' => 'This email can not be taken.'],

还有这个

[['first_name'], 'string', 'min' => 4, 'max' => 50,
            'when' => function ($model, $attribute) {
                $this->isNewFirstName = false;
                if($model->$attribute != User::find()->where(['id' => Yii::$app->user->id])->one()->first_name) {
                    $this->isNewFirstName = true;
                }
                return $this->isNewFirstName;
            },
        ],

以此类推

我能做些什么来消除这个代码重复。或者像我这样的情况,是否有 Yii2 存在的模块或组件?或者是否有某个地方存在我的问题的核心验证器?或者我注定要永远重复所有这些代码?)

您可以看到 2 个 when 可调用函数具有相同的结构。所以你可以写一个像这样的简单函数:

/**
 * @param $model ActiveRecord
 * @param $attribute string
 * @return bool
 */
public function checkUniqueAttribute($model, $attribute)
{
    return $model->$attribute != $model::find()->where(['id' => Yii::$app->user->id])->one()->$attribute;
}

并在您的规则中使用它:

[
    ['new_email'], 'unique',
    'targetAttribute' => 'email',
    'targetClass' => '\common\models\User',
    'message' => 'This email can not be taken.',
    'when' => 'checkUniqueAttribute',
],
[
    ['first_name'], 'unique',
    'targetAttribute' => 'first_name',
    'targetClass' => '\common\models\User',
    'message' => 'This first name can not be taken.',
    'when' => 'checkUniqueAttribute',
],
[['first_name'], 'string', 'min' => 4, 'max' => 50,],

希望有用。

祝你好运,玩得开心!