Yii restricts read-only database connection

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

Although I can set up a read-only database user account, there are other people managing this system, and I want the application-level redundancy to be completely prevented by unintentional entries using standard ActiveRecord Yii classes.

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

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/

+6
source share
3 answers

The link you provided on the Yii forums has an extension that handles this for you: http://www.yiiframework.com/extension/dbreadwritesplitting

I would probably look at this first if you have many AR models. You can follow the path of behavior (as suggested in this forum) as another option.

But whatever you do, you will want to override beforeSave / afterSave instead of onBeforeSave / onAfterSave. These methods are designed to trigger events, and not to run their own custom code. And, for another of the forum posts , you will need to set your AR db variable with a static call. So the code of Sergey should 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 {} ... 
+4
source
 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 {} ... 

U need to try this way :) But IMHO this is not good enough. I think there will be some mistakes or shortcomings

+2
source

Given the scenario where your subordinate cannot update the master, you might run into problems. Because after updating the data you might read from the old version.

Although these approaches on the forum are very clean and written by authors who are mainly Yii masters. I also have an alternative. You can override the getDbConnection () method in AR, for example

 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 when switching database connections, you still have to be careful.

+2
source

Source: https://habr.com/ru/post/919996/


All Articles