2

我已经实现了一个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...
    }
}

任何帮助,将不胜感激。参考链接:地穴行为

4

2 回答 2

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....
于 2012-10-29T12:42:22.107 回答
0

您还必须将类的static model功能添加到子类中。就这么多应该工作:

public static function model($className=__CLASS__)
{
    return parent::model($className);
}
于 2012-10-26T13:43:30.493 回答