Activerecord 子类中的Yii模型行为继承了AR模型类
我已经实现了一个Activerecord 子类中的Yii模型行为继承了AR模型类,activerecord,yii,behavior,Activerecord,Yii,Behavior,我已经实现了一个cryptbehavior类,它可以附加到AR模型,这样附加的属性将以加密的形式存储,并以解密字符串的形式检索 class User extends CActiveRecord { public function behaviors() { return array( 'crypt' => array( // this assumes that the behavior is in the f
crypt
behavior类,它可以附加到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
表中做了一些更改并重新生成模型,我就不会丢失自己的函数
如果我将我的行为
函数移动到类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...
}
}
任何帮助都将不胜感激。
参考链接:您还必须将类的
静态模型
函数添加到子类中。就这么多应该有用:
publicstaticfunctionmodel($className=\uuuuu CLASS\uuuu)
{
返回父::模型($className);
}
以下是有效的解决方案。我需要测试所有的场景。感谢@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....
我在任何地方都找不到cryptbehavior扩展,这是你自己的行为吗?可以粘贴行为的大致轮廓,它扩展了哪个类,实现了哪些函数就足够了。用引用链接更新了帖子!。谢谢你的关注。没问题,让我看看我是否能帮上忙。我想这个博客给了我一些实现我想要的路线图。哪个版本的yii是你的?实际上你提供的博客链接也是正确的,但是在yii版本的某个地方,添加了该功能。我将在发生此更改时更新答案,并在稍后更新更多详细信息,至少现在您不应该在答案中出现错误。尝试引入一些不接触基本模型类的常见做法。谢谢你的回复。我也在寻找DB组件级别的附加行为,这样我就可以避免这个prob.bool.dev你住在这里吗?让我回答一些问题!:P