Yii 限制数据库连接为只读 [英] Yii restrict database connection to read-only

查看:23
本文介绍了Yii 限制数据库连接为只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据库连接,一个用于我的大部分应用程序数据,一个仅用于读取.

I have two database connections, one that is used for most of my application data, and one that is only used for reads.

虽然我可以将我的数据库用户帐户设置为只允许读取,但还有其他人管理这个系统,我希望在应用程序级别有一些冗余,以绝对防止使用 Yii 的标准 ActiveRecord 类进行意外写入.

Although I can setup my database user account to only allow reads, there are other people administering this system, and I want some redundancy at the application level to absolutely prevent unintended writes using the Yii's standard ActiveRecord classes.

在论坛上找到了这一点信息,但想知道是否有人可以确认这是一种好方法和/或建议另一种方法.

Found this bit of information on the forums, but was wondering if someone could confirm that this is a good approach and/or suggest another one.

public function onBeforeSave($event)
{
   $this->db = Yii::app()->masterDb;
}

public function onAfterSave($event)
{
   $this->db = Yii::app()->db;
}

http://www.yiiframework.com/forum/index.php/topic/5712-active-record-save-to-different-server-load-balancefail-over-setup/

推荐答案

根据您提供给 Yii 论坛的链接,有一个扩展可以为您处理此问题:http://www.yiiframework.com/extension/dbreadwritesplitting

Per that link you provided to the Yii forums, there's an extension that handles this for you: http://www.yiiframework.com/extension/dbreadwritesplitting

如果你有很多 AR 模型,我可能会先研究一下.您可以将行为路线(如该论坛帖子中建议的那样)作为另一种选择.

I'd probably look into that first, if you've got a lot of AR models. You could go the Behavior route (as suggested in that forum post) as another option.

但是无论你做什么,你都会想要覆盖 beforeSave/afterSave 而不是 onBeforeSave/onAfterSave.这些方法用于触发事件,而不仅仅是运行您自己的特殊代码.而且,根据 另一篇论坛帖子,您需要使用静态调用设置您的 AR db 变量.所以 Sergey 的代码实际上应该是:

But whatever you do, you are going to want to be overriding beforeSave / afterSave instead of onBeforeSave / onAfterSave. Those methods are for triggering events, not just running your own special code. And, per another one of the forum posts, you'll need to set your AR db variable using a static call. So Sergey's code should actually be:

class MyActiveRecord extends CActiveRecord
{
    ...
    public function beforeSave()
    {
       // set write DB
       self::$db = Yii::app()->masterDb;

       return parent::beforeSave();
    }

    public function afterSave()
    {
       // set read db 
       self::$db = Yii::app()->db;

       return parent::beforeSave();
    }
    ...
}


class User extends MyActiveRecord {}
class Post extends MyActiveRecord {}
...

这篇关于Yii 限制数据库连接为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆