How do you handle this generic situation of saving data. Do you have a model and pass a db connection to the model? Or do you have a db repository and then mass the model to the db repo?

I think that's clear. I've done both and I'm curious to see what people think. Would you rather have:

$model = new Model($conn);

or

$dbRepository->save($model)

Pros and cons of either solution? What do you do and why?

Posted Aug 2, 2018, 4:21 PM UTC

13
YMK1234•

The latter. I am a strong believer in not having any sort of logic in DTOs (though honestly so is everyone I know)

1
anamorphism•

also the latter for me.

in the first, your model of an object now knows about how that data is being stored. it really doesn't need to have that knowledge. if you change databases, you now have to update every single one of your model classes.

1
thebagel•

Another vote for the latter. I'm a strong believer in separation of concerns. The specific concern for the model is holding data, while the specific concern for the repository is saving and retrieving models.

The benefit of this model is that you can talk about a model without caring where it came from. You can create a model and test code that uses it without actually configuring a database. If you decide you don't like your original datastore, you can implement a new one that uses the same model types without rewriting everything that touches your model.

A disadvantage of keeping the connection and datastore logic within the model itself is that any code that needs to create a model also needs to know how to talk to the database. The end result is that your database logic has poisoned your code - everything that could ever touch a model needs to know about the database.

I'll note that I haven't seen the first pattern in live code in a very long time, and I don't know anyone who prefers that style now, primarily because it is so much harder to test and maintain.

1