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条)

报告相同问题?