dpxkkhu1812 2012-07-09 01:47
浏览 65
已采纳

Yii将数据库连接限制为只读

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

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/

  • 写回答

3条回答 默认 最新

  • dsjuimtq920056 2012-07-16 01:10
    关注

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

    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.

    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 {}
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂