Php Yii:beforeValidate具有相同代码的2个模型

Php Yii:beforeValidate具有相同代码的2个模型,php,yii,content-management-system,yii-cmodel,Php,Yii,Content Management System,Yii Cmodel,我有一个Yii应用程序,在其中两个模型中,我有beforeValidation方法的代码 yii对此是否有解决方案,或者我是否应该创建一个组件并使用此通用代码的参数?您可以创建一个类,该类可由您的模型扩展: class CommonClass extends CActiveRecord { public function beforeValidate(){ ... } } class A extends CommonClass{ } class B exte

我有一个Yii应用程序,在其中两个模型中,我有beforeValidation方法的代码


yii对此是否有解决方案,或者我是否应该创建一个组件并使用此通用代码的参数?

您可以创建一个类,该类可由您的模型扩展:

class CommonClass extends CActiveRecord
{

    public function beforeValidate(){
       ...
    }

}

class A extends CommonClass{
}

class B extends CommonClass{
}
或者您可以定义一个行为并将此行为添加到两个模型中

class YourBehavior extends CActiveRecordBehavior
{
    public function beforeValidate($event)
    {
        ...
    }
}

class A extends CActiveRecord{
    public function behaviors(){
    return array(
        'YourBehavior' => array(
            'class' => 'components.YourBehavior',
        ),      
    );
}
}

class B extends CActiveRecord{
    public function behaviors(){
    return array(
        'YourBehavior' => array(
            'class' => 'components.YourBehavior',
        ),      
    );
}
}

您可以创建一个模型都扩展的类:

class CommonClass extends CActiveRecord
{

    public function beforeValidate(){
       ...
    }

}

class A extends CommonClass{
}

class B extends CommonClass{
}
或者您可以定义一个行为并将此行为添加到两个模型中

class YourBehavior extends CActiveRecordBehavior
{
    public function beforeValidate($event)
    {
        ...
    }
}

class A extends CActiveRecord{
    public function behaviors(){
    return array(
        'YourBehavior' => array(
            'class' => 'components.YourBehavior',
        ),      
    );
}
}

class B extends CActiveRecord{
    public function behaviors(){
    return array(
        'YourBehavior' => array(
            'class' => 'components.YourBehavior',
        ),      
    );
}
}

这也是我一直在想的,但我认为yii有一个针对这个案例的预构建解决方案。就我对yii的了解而言,这些是我所知道的唯一解决方案。但是声明一个行为真的很容易,我不知道有什么“预构建解决方案”比你想象的更容易!weel,我只是想知道,这没什么特别的,它与类的正常环境这是我也在想的,但我认为yii有一个针对这种情况的预构建解决方案。嗯,就我所知,yii是我所知道的唯一解决方案。但是声明一个行为真的很容易,我不知道有什么“预构建解决方案”比你想象的更容易!weel,我只是想知道,这没什么特别的,这是一个正常的上课环境