I’ve set up my site where I have submodels depending on the the type specified in the row. So let’s say I’ve got a table called `animal` and each row has a `type` column where it could be dog, cat, or some other predetermined value. I’ve created a model for dog and a model for cat. When I find a row out of the database I pass it to a factory method that well convert it from an Animal model into a Dog model. So I do one find to get the first row. Once I have the row I know what type it is. My options at that point are to either do another find on the same row with the correct submodel, or to instantiate a new submodel and set the attributes. I went with option two. The problem is, when I try to `save()` it, it does an insert and when I delete it, it doesn’t know what the primary key is. Turns out there’s a function you can use that converts it from a new model into an old model:
That solved my problem!
This probably isn’t the best design pattern. What are your thoughts? How would you handle dynamic models? One idea I had, but haven’t implemented yet would be to do dependency injection. Instead of my Dog model extending the Animal model, the Dog model would some other type of class that accepts the Animal model as a parameter for the constructor. Other ideas?