I have some experience trying to get polymorphism to work (including polymorphic files) in symfony, and at this point I think I can share some of my thoughts with you in the hope that they will provide you with useful information about this topic.
First, I would suggest reading the doctrine of inheritance mapping link . With doctrine inheritance mapping, you would simply create one main File class and then add all the other applications. Then, say you want to add an attached image to the user. You would simply create a oneToOne relationship between the user and the main File class. If the attachment you save is an instance of one of the attachment classes, Doctrine is smart enough to return an object of that class, not the main File class.
To answer your question, I will give you a concrete example. Case
- ImageAttachment extends FileAttachment
- The user has a property called photo.
- Property Photos - OneToOne Relationship to FileAttachment
The code:
$image = new ImageAttachment(); $user->setPhoto($image); $em->persist($user); $em->flush();
Result:
Now in the database in the User table in the column named something like photo_id, the reference identifier will be listed in the FileAttachment table. When you will do $ user-> getPhoto (); it will return an object of the ImageAttachment class, because the doctrine knows that you saved ImageAttachment, not just FileAttachment.
When it comes to collections, everything will be pretty simple. In this case, you probably need to create ManyToMany relationships between the file and the object that you want to associate with the file. Suppose a user can have many different types of attachments stored in a database. If you want to use this application for the file system, it probably makes no sense for the file to know about the user to whom it belongs, because soon the file will have to store information about all the different types of relationships, and this is simply not a smart architecture if you want to have modular system of any type. That's why my suggestion is to use ManyToMany relationships between some objects and attachments. Thus, only the user would know about the files in the database, and the file system would be agnostic and decoupled.
The third important thing to do when it comes to polymorphism in the doctrine is symfony support for this function. As a rule, polymorphism is considered in some cases bad practice, and especially in data storage does not provide significant support in the community. Therefore, it is important to consider that symfony CollectionType DOES NOT SUPPORT POLYMORPHISM, which is always the case . Basically, you will have to write your own type if you plan on using collections of polymorphic forms. But if you don't mind using a bit of ajax, this is not a problem, you can simply avoid using SF forms for this purpose.
grssn
source share