matt-allan / quicksilver

A demo bike messenger app, demonstrating BDD and Hexagonal Architecture in PHP
43 stars 5 forks source link

Quicksilver\Domain\User has a private field that is never set #1

Open rulatir opened 7 years ago

rulatir commented 7 years ago

The abstract class \Quicksilver\Domain\User has private field $id that is never set. This is a big WHOA. I can see that elsewhere in this example's code reflection hacks are used to set private fields on objects. Since this is a basic tutorial application that is supposed to teach BDD and hexagonal architecture, a question naturally arises: does either BDD or hexagonal architecture necessitate such hacks, or is the author's choice to use them independent of the concepts and methods being taught? If it is independent, then I believe it is a wrong choice because it introduces an irrelevant complication.

matt-allan commented 6 years ago

Hi,

Sorry I didn't see the notification for this.

The auto increment ID is kind of a special case. It doesn't ever get set by application code; The only code that ever sets it is behind an interface.

I personally think it's fine to use reflection to set it in this case. The alternative would be adding a setter that is only ever used by the repositories (or a hydrator or something). That is fine too. For me it's not worth it since I am only ever using repositories that already use reflection for setting the ID.

Another (probably the best) solution is to use a UUID. Then you can require the ID in the constructor and your entity doesn't change when it comes back from the repository. I like that solution a lot and use it when I can.

These repos are pretty strongly influenced by how we write code at my day job so there are definitely some aspects that are influenced by my personal preferences. We use doctrine and auto increment IDs at work so that is what I went with. I agree that an example that didn't rely on magic would probably better illustrate the core concepts 😁