Is it possible to create DB Data Mapper in Yii2?

Hi. I have the next task. We’ve already developed app. But now we need to change our DB to another one (it’s used in other apps, so we have to use it without changes). Set of fields in the new DB are the same, but field names are different (like, was “user_id” became “userID” etc.)

What is the best option to achieve that? I thought maybe some "mapping is possible"? So when I use $post->user_id AR understand it as $post->userID

In that case things like <?= $form->field($model, ‘user_id’)->textInput() ?> will continue working.

Or do I need to implement some setters/getters?

Any ideas?

Is it possible to create Data Mapper in Yii2?

AFAIK Yii itself does not have any kind of ‘mapper’.

You can either user getters/setters, or solve this task at DB side (for example, PG has this:

We are using MySQL. Do you know what is possible in this case?

It’s interesting situation that you have.

Is it a big database? I’m asking because if it is not to change names in database from camelCase to underscore.

Other solution is of course to go through all the code and simply change where you have something like this $customer->total_amount to $customer->totalAmount but this you already know and it will take time to do this. I don’t know how many code do you have.

One solution also is to add to your active record models all the fields that you have as underscores something like this.

class Customer extends ActiveRecord{

   public $total_amount;

   public function init(){

      $this->totalAmount =& $this->total_amount;




To be honest I don’t know if this would work but in this way you are building you own mapper. If this doesn’t work than maybe you could use behaviour that will set this 2 variables on events like before save and so on. You put events on what you want that this mapping needs to happen. Check references on php manual.

I hope I helped.