Yii2: Manually Loading a Model

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:


$myModel->setIsNewRecord(false);

That solved my problem!

Notes

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?

I've always worked as an innovative programmer. My insights and creative thinking result in superior products and customer satisfaction. Working full time as a senior web architect I've used lots of exciting technologies (i.e., Ember, Backbone, Handlebars, etc) and developed a lot of exciting sites. In my spare time I hope to develop even more exciting and new technologies. I've been programming professionally for 9 years in everything from desktop applications to web applications to mobile applications.

Posted in Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

About the Author

  • Chris LondonSenior Web ArchitectPartners In Leadership

    I've always worked as an innovative programmer. My insights and creative thinking result in superior products and customer satisfaction. Working full time as a senior web architect I've used lots of exciting technologies (i.e., Ember, Backbone, Handlebars, etc) and developed a lot of exciting sites. In my spare time I hope to develop even more exciting and new technologies. I've been programming professionally for 9 years in everything from desktop applications to web applications to mobile applications.

    Web: https://plus.google.com/116403409191372324375