子类中的Yii模型行为继承了AR模型类

时间:2012-10-26 09:13:28

标签: activerecord yii behavior

我已经实现了一个crypt行为类,可以附加到AR模型,以便附加属性将被加密存储并作为解密字符串检索。

class User extends CActiveRecord 
{
    public function behaviors()
    {
        return array(
            'crypt' => array(
            // this assumes that the behavior is in the folder: protected/behaviors/
            'class' => 'application.behaviors.CryptBehavior',
            // this sets that the attributes to be encrypted/decrypted are encryptedfieldname of the model
            'attributes' => array('password'),
            'useAESMySql' => true
           )
        );
    }
}

这很好用。我也有我的自定义类Myuser扩展User模型来编写我的自定义函数,这样如果我在user表中进行一些更改并重新生成模型,我就不会失去自己的函数。

如果我将behavior功能移至课程MyUser该行为未获得附加且未按预期工作

class MyUser extends User 
{
    public function behaviors()
    {
        return array(
            'crypt' => array(
            // this assumes that the behavior is in the folder: protected/behaviors/
            'class' => 'application.behaviors.CryptBehavior',
            // this sets that the attributes to be encrypted/decrypted are encryptedfieldname of the model
            'attributes' => array('password'),
            'useAESMySql' => true
           )
        );
    }

    public function customfn1()
    {
         //some code goes here...
    }
}

任何帮助将不胜感激。 参考链接:Crypt Behavior

2 个答案:

答案 0 :(得分:1)

这是工作解决方案。我需要测试所有场景。感谢@ bool.dev为您的功能。

class MyUser extends User 
{
    public static function model($className=__CLASS__)
    {
       return parent::model($className);
    }

    public function behaviors()
    {
        return array(
            'crypt' => array(
            // this assumes that the behavior is in the folder: protected/behaviors/
            'class' => 'application.behaviors.CryptBehavior',
           // this sets that the attributes to be encrypted/decrypted are encryptedfieldname of the model
            'attributes' => array('password'),
           'useAESMySql' => true
          )
       );
    }

   public static function getUserByID($id)
   {
      //validation of $id goes here..

      return MyUser::model()->findByPk($id);
   }
}

在我的控制器中

$userModel = MyUser::getUserByID(1);

在我看来

$userModel->password; //gives me the decrypted password; for easy understanding, i used password field here....

答案 1 :(得分:0)

您还必须将类的static model函数添加到子类中。这应该有用:

public static function model($className=__CLASS__)
{
    return parent::model($className);
}