Symfony2 - rendering a subclass attribute of an object that is referenced as an instance of the superclass
Here's a problem I've been running into all day ...
I have a superclass named Message
:
class Message
{
protected $id;
protected $body;
protected $sender;
protected $receiver;
// [...]
from which my class inherits Bill
:
class Bill extends Message
{
protected $id;
protected $amount;
And I wanted to create a dialog class that collects multiple messages (like invoices):
class Dialogue
{
protected $id;
protected $subject;
protected $messages = array();
And here is the relevant mapping (YAML, Mongodb):
Bundle\Document\Dialogue:
repositoryClass: Bundle\Repository\DialogueRepository
fields:
id:
id: true
subject:
type: string
referenceMany:
messages:
targetDocument: Message
cascade: [remove]
The problem is, when I try to display some Bill specific attributes (for example in Twig :) dialogue[0].messages.amount
I get this error:
The sum method does not exist for the MongoDBODMProxies__CG __ \ Bundle \ Document \ Message object.
I think I figured out that my bill counts as a Message and not a Bill ... Also, I don't think it is possible in PHP to typecast to make sure it counts dialogue.message[0]
as a bill ... What can I do to access these specific attributes?
Reference: (
PS: I may have a hint: this error occurs when I load the dialog objects from the corresponding repository. However, if I create a new dialog and a new bill in the controller and pass them directly, everything works correctly.
So I tried $ get_class ($ bill) before and after saving the Bill object and this is what I got:
- before saving: Bundle \ Document \ Bill
- after saving + loading from repo: MongoDBODMProxies__CG __ \ Bundle \ Document \ Message
My problem might come from here, right?
source to share
This is a design problem. Dialogue
contains a collection Messages
that has nothing to do with the subclass or not.
Either you provide all types Message
with a generic Interface
one that has all the properties available, or you explicitly provide your object with a Dialogue
separate relation for each type Message
you want to assign it, for example:
Bundle\Document\Dialogue:
...
referenceMany:
messages:
targetDocument: Message
cascade: [remove]
bills:
targetDocument: Bill
cascade: [remove]
...
source to share