I often use helper methods in my models. For example, if my model has a ‘date’ property, I might have getDateShort() or getDateLong() methods. Is it ok to put these methods in my entities, or should I wrap a model class around the entity and consider the entity as a model resource?
Share
This is a pretty broad question.
In general, there’s nothing wrong with adding those kinds of methods to your entities directly. A good rule of thumb is that such methods are okay if they only concern themselves with data internal to the entity.
That said, doing things like formatting dates might be better put into some external helper class, as you might want to do consistent formatting on dates from several different entity classes.
With your date example, you might consider just implementing a getter that can take an optional parameter, that you could use like this:
In that example, we assume there are some globally defined MY_DATE_FORMAT_* constants. For more specific-to-this-entity type things, you might define class constants instead.
Going back to your question, here’s another example of something I think is perfectly okay to do inside an Entity:
So various bits of internal (either directly, or via associations) data go into computing the order total. But since it’s only internally-visible data, it makes good sense to include getTotal() as a method on Order.
If, on the other hand, you were making API calls to some shipping service to include shipping charges in the total, it would make more sense to keep that complexity away from the entity, in some sort of service class.