Lets say that I have a shelf on which I can put items that are shelfable (not sure if that is actually a word but you can understand my point). So I have the following:
class Shelf
{
/** @var ShelfableItemInterface[] **/
private $items = [];
// addItem, getItems...
}
interface ShelfableItemInterface
{
}
/** let's imagine that not all books are shelfable **/
class Notebook extends Book implements ShelfableItemInterface
{
}
class PhotoFrame implements ShelfableItemInterface
{
}
So those are the definitions, and now I can create shelfs with different items on them:
$shelf = new Shelf();
$shelf->addItem(new Notebook(...));
$shelf->addItem(new PhotoFrame(...));
$shelf->addItem(new PhotoFrame(...));
// will return the three items
var_dump($shelf->getItems());
So, this works perfectly while all that data is not persisted and retrieved from storage.
I'm currently using Doctrine ORM which can automatically fetch the related objects and instantiate the objects of their proper classes, but that only works if all the related items extend same class which should be set in the relationship definition.
This is a problem as I don't want to be forced to make the related items extend some class (as we can see the Notebook already extends something), but make the relationship work by interface.
I know that I still would have some mapping strategy (or however we should call that), so for example in the database we'll have a table with the following:
+----+---------+-----------+
| id | shef_id | item_type |
+----+---------+-----------+
| 1 | 5 | 1 |
| 2 | 5 | 2 |
| 3 | 5 | 2 |
+----+---------+-----------+
(additional data in tables per type)
So, I'm confused how to make this work or where to put the process, in order for the ORM (or my logic) to know that when I call getItems(), when fetching the related items, if "item_type" is 2, it should instantiate object from PhotoFrame, 1 for Notebook etc.
I don't know if I stated my problem clearly, but I hope you can understand me.
Update: I see that this is available in java - http://jpaobjects.sourceforge.net/m2-site/main/documentation/docbkx/html/user-guide/ch04s09.html without the class inheritance part, but I would like to learn how I can achieve this in php without such library