I initially decided to understand the solution to your problem, but the more I think about it, I think your logic is corrupted.
I see how the fact that the tables are similar or identical can lead to a decision to use the same model to interact with both tables. However, when you look at what a model should be (CakePHP basically has a table interface), it makes no sense to switch back and forth.
CakePHP docs explain the models as follows:
In object-oriented programming, a data model is an object that represents a “thing”, such as a car, person, or home.
In your example, you really have two separate “things” that look exactly the same. Therefore, they must have their own models.
If your models really have the same methods, then the “CakePHP path” will define a custom Behavior that encapsulates your common methods. Then attach the behavior to both models.
Then you can load the desired model in the controller state:
private $DynamicModel; public function saveProduct() { if (condition) { App::import('Model', 'ModelZ'); $this->DynamicModel = new ModelZ; } else { App::import('Model', 'ModelY'); $this->DynamicModel = new ModelY; } $this->DynamicModel->save($this->data); }
Stephen
source share