Search code examples
inheritancedoctrine-ormdiscriminator

Setting the discriminator dynamically in Doctrine2


I have a Parent entity with 2 child entities (Foo and Bar) implementing SINGLE_TABLE inheritance.

Is it possible to create a new Parent() entity and dynamically set it's discriminator to foo instead of creating a new Foo() ?


Solution

  • No, there isn't, if you really need the scenario mentioned in your comment, then you'll probably be better with some kind of factory method:

    abstract class MyParent
    {
        public static function fromString($type)
        {
            switch ($type) {
                case 'foo':
                    return new Foo();
                case 'bar':
                    return new Bar();
            }
            throw new DomainException('Unknown type: ' . $type);
        }
    }