cevou
cevou

Reputation: 325

Symfony2 Doctrine Get reference based on attribute

in my Symfony2/Doctrine2 project I have an entity Person which has a birth date. I have another entity Agegroup which stores a name and some more information for a group based on the age in years.

Example:
Person Name: xy Date: 1980-05-06
Agegroup: From: 1 To: 10
Agegroup: From: 11 To: 20
Agegroup: From: 21 To: 30

I want to get the Agegroup which a person currently belongs to, from within the entity (based on current date).

i.e. :$person->getCurrentAgeGroup()

Therefore I would have to access another repository class from within the entity, which is obviously not a good thing to do.

Is there a way to implement this kind of functionality?

I read Using EntityManager inside Doctrine 2.0 entities which could be a solution to the problem. Unfortunately I didn't find a solution to implementent this. Do I have to inject the service somehow into the entity?

Maybe there are other best practices for this kind of problem?

Upvotes: 1

Views: 1085

Answers (1)

chiborg
chiborg

Reputation: 28084

It is not good style to put the entity manager into your entities. A better approach would be to create a custom AgegroupRepository that has a method getAgegroup(Person $person)

Another approach would be to make the age group a property of Person (with getters and setters), create a custom PersonRepository and modify the find() method to instantiate the correct instance of Agegroup when looking for a person.

Your entity objects should only store data and business rules and should not concern themselves with the storage of the information. This is what repositories are for.

Upvotes: 2

Related Questions