PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 1, 2022

[FIXED] How to deal with calculated entity attribute

 August 01, 2022     doctrine, entity, symfony     No comments   

Issue

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.



Answered By - Jakub Zalas
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing