ARTICLE AD BOX
I am using PHP 8 attributes with Doctrine ORM in Symfony.
I want to reuse the same ownership relation across many entities such as Website, Spot, Ad, etc.
My goal is:
use one reusable trait for the owning side
avoid repeating the same getUser() / setUser() logic in every entity
avoid adding separate inverse collections like websites, spots, ads on User
Example trait:
trait UserOwnerTrait { #[ORM\ManyToOne(targetEntity: User::class)] #[ORM\JoinColumn(nullable: false)] private ?User $user = null; public function getUser(): ?User { return $this->user; } public function setUser(?User $user): static { $this->user = $user; return $this; } }Used in multiple entities:
#[ORM\Entity] class Website { use UserOwnerTrait; } #[ORM\Entity] class Spot { use UserOwnerTrait; } #[ORM\Entity] class Ad { use UserOwnerTrait; }What I want to avoid on User is this kind of per-entity inverse mapping <- so this part is what i need ebcause of relations will not just simple work
#[ORM\Entity] class User { #[ORM\OneToMany(mappedBy: 'user', targetEntity: Website::class)] private Collection $websites; #[ORM\OneToMany(mappedBy: 'user', targetEntity: Spot::class)] private Collection $spots; #[ORM\OneToMany(mappedBy: 'user', targetEntity: Ad::class)] private Collection $ads; }I know Doctrine has loadClassMetadata and runtime metadata manipulation, so my question is:
Is it actually supported to generate these inverse mappings dynamically for all entities using the trait, or does Doctrine fundamentally require a concrete inverse field per association on the target entity?
If it is not supported, is the correct approach simply to keep the relation unidirectional and query related entities via repositories instead of trying to model inverse collections on User?
so just again, shorter... maybe my details were too confusing:
I want just like to have 1 single trait UserOwnerTrait and just to use it for all entities that have relation to User, only using trait and NOT using any additional methods at all
