Search code examples
symfonydoctrineentity

How to deal with calculated entity attribute


Let's say there is an entity called Staff.

It has a number of persistent attributes, such as: - Name - Experience - Age

I want to create a "virtual" attribute, that is based on the Experience and Age, called 'Salary'. For example: $salary = ($experience + $age) * 100

But I don't want to persist the Salary attribute. The reason is that I want to let the Salary attribute get's updated automatically whenever the age or experienced values change.

I have two questions regarding this:

  • Is the Entity file a good place to store the getSalary() function?
  • How can I make it so that whenever a Staff entity is called, the salary variable will be filled with the salary that is calculated based on age & experience?

Solution

  • Is the Entity file a good place to store the getSalary() function?

    Yes, it is.

    Not every field in your entity has to be mapped to a database field.

    Also, entities can contain methods other than simple getters and setters. IMO as long as those methods operate on the entity fields, they belong to the entity.

    How can I make it so that whenever a Staff entity is called, the salary variable will be filled with the salary that is calculated based on age & experience?

    You could use one of the Doctrine's lifecycle events, for example the postLoad event, which is called after entity is loaded to the entity manager.

    Note, that you don't have to be storing calculation results in a property. Your calculation is simple and it's probably better to define a getter.