【问题标题】:Yii: 2 models with the same code for beforeValidate [closed]Yii:2个具有相同代码的模型 beforeValidate [关闭]
【发布时间】:2013-03-29 08:42:57
【问题描述】:

我有一个 Yii 应用,在 2 个模型中,我有 beforeValidation 方法的代码。

yii 有解决方案,还是我应该为这个通用代码创建一个组件并使用参数?

【问题讨论】:

    标签: php yii content-management-system yii-cmodel


    【解决方案1】:

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

    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,我只是想知道,这没什么特别的,它的正常环境与类
    猜你喜欢
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多