One Model, Controller And Views On Multiple Tables

This is the situation.

I have 2 by structure the same tables but different by name. It is because it is easier to track data for me.

What I would like to do is to have one controller, one model and one views for that 2 tables.

Now I have model, controller and view for each of them. And I have to change the same lines of code on both of them when I try to make changes. Not efficient.

Is there any better way. Even the code I’m using on both models, controllers and views are the same, just data from database isn’t.

use object programming for models…




class ModelA extend CActiveRecord {

  public function tableName() {

	return 'table_1';

  }


...

...full model code

....

}


class ModelB extends ModelA {

  public function tableName() {

	return 'table_2';

  }

}



for controllers it is slightly different because ActiveForms and actions generated by Gii depend on model name like in this example:




if(isset($_POST['ModelA'])) {

  $model->attributes = $_POST['ModelA'];

  $model->save();

}



also actions need to instantiate proper model, but with little coding and magic of “get_class($model)” you can achieve also similar effects :)

I know that. That is what I have right now 2 models for 2 controllers.

But I wanted to use one mode one controller and one views to display and store data from 2 different tables.

Code and every single thing is exactly the same in both models and controllers

Possible solution that crossed my mind:

allow user to pick which "table" he wants. Set session variable or cookie depening his choice.

Nex in model read session variable or cookie (maybe better cookie so you won’t have to start_session in every page you need it)and load/use different tables :D


	public function tableName()

	{

               if($_COOKIE['xxx']=="choice1")

		   return '{{table1}}';

              else

                    return '{{table2}}';


	}

it would probably work, but it is not very good programming pattern and is very insecure (user can alter its cookie and change table he is working with).

ActiveRecord pattern is very closely related to table (one AR model = one table)

In my opinion - if you have two tables you should have two models. you can only share some logic between them so you do not have to copy&paste all further changes. You can also easily share views between controllers…

You are probably right. Thanks, I might have idea how to alter something, not all, but it’s fine :)