2

I've been trying to incorporate the repository pattern into my PHP app, loosely following this example.

I'm trying to decide between:

  1. limiting which fields I retrieve from a database
  2. retrieving all of them and storing them in a domain object.

The accepted answer in the topic I linked shows a way to implement option 1. The second answer shows why it may be better to retrieve full objects instead.

In my case, retrieving full objects often involves getting from 50 to 250 fields. Retrieve an array of those objects, and that's gonna be a lot of fields which could affect performance of the app. That's why I've been leaning towards being selective about which fields I retrieve, since I usually need up to 10 to perform common operations.

If I take the selective approach, then I wouldn't be able to use domain objects to store the data, and I may face the issues that "the second answer" mentioned.

  1. You end up with essentially the same data across many queries. For example, with a User, you'll end up writing essentially the same select * for many calls. One call will get 8 of 10 fields, one will get 5 of 10, one will get 7 of 10. Why not replace all with one call that gets 10 out of 10? The reason this is bad is that it is murder to re-factor/test/mock.
  2. It becomes very hard to reason at a high level about your code over time. Instead of statements like "Why is the User so slow?" you end up tracking down one-off queries and so bug fixes tend to be small and localized.
  3. It's really hard to replace the underlying technology. If you store everything in MySQL now and want to move to MongoDB, it's a lot harder to replace 100 ad-hoc calls than it is a handful of entities.

I could still use domain objects for Create Update and Delete operations, but Read operations would have to be stored in plain objects or associative arrays, as per the CQRS pattern. I do have some more complex queries currently that involve joins, which would be difficult to replicate with domain objects, without doing extra DB calls and processing that the database would normally handle in 1 query.

Given all of this, does it make sense for me to use domain objects for just read operations, or at all? Am I missing some other advantages that the domain objects can provide to help with the concerns I've stated?

Cohaven
  • 163
  • 1
  • 10
  • This is an excellent question I've been thinking about this. I think like everything in software engineering there is no correct answer, there are only pros and cons. I would like to hear more from some experienced engineers. – brainoverflow98 Dec 31 '19 at 17:15

0 Answers0