Bartosz Rychlicki
Bartosz Rychlicki

Reputation: 1918

How to make dynamic associations in Doctrine based on dynamic variable?

Im quite new to doctrine2. I need to make a connection like this:

Tag has a (abstract) resource connected. (abstract) resource has tags.

I want to danamicly type the object of the Entity resource based on code. So this way I can attach tags to any entity that implements given interface.

Im using Zend Framework and annotations docblock style in doctrine.

Another example would be a "Message" Entity with repesents a text message in system, it have an author and recipient associations, but I want to have diffrent targets for them depending of the author and recipient. For example Admin Entity sends a message to User Entity, or User Entity sends a message to a VipUser Entity.

Upvotes: 2

Views: 2813

Answers (2)

Gedrox
Gedrox

Reputation: 3612

Check out this doctrine2 extension:

https://github.com/FabienPennequin/DoctrineExtensions-Taggable

I believe this will do what you want.

Upvotes: 1

Lee Davis
Lee Davis

Reputation: 4756

Sounds like Class Table Inheritance is the perfect solution for this.

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/inheritance-mapping.html#class-table-inheritance

You essentially need to create your parent class (tags) and provide a discriminator map for each of its children. So for example..

/** 
 * @Entity 
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"tag" = "Tag", "message" = "Message", "otherentity" = "OtherEntity"})
 */
class Tag
{
   // tag properties / definitions etc
}

/** @Entity */
class Message extends Tag
{
   // Message specific stuff
}

you can extend your "Tag" entity on any other entity you need. Just remember to update your discriminator map values for it.

Upvotes: 2

Related Questions