Yii restrict database connection to read-only

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 {}
...

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

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


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

You have to try that way. But in my opinion, it's not good enough. I think there will be some bugs or defects.


Given a scenario where your slave can't update with the master, you might run into problems. Because after updating data you'll maybe read from an old version.

While the given approaches in the forum are very clean and written by authors which are mostly Yii wizards. I also have an alternative. You may override the getDbConnection() method in AR like

public function getDbConnection(){
  if (Yii::app()->user->hasEditedData()) { # you've got to write something like this(!)
     return Yii::app()->masterDb;
  } else {
     return Yii::app()->db;
  }
}

But you still have to be careful when switching database connections.

Tags:

Php

Yii