Can I access discriminator field from php in doctr

2019-01-08 19:02发布

I have an entity which defines inheritance like this:

* @DiscriminatorColumn(name="type", type="string")
* @DiscriminatorMap({"text" = "TextAttribute", "boolean" = "BooleanAttribute", "numeric" = "NumericAttribute", "date" = "DateAttribute"})

I am wondering is it possible to have getter for field 'type'? I know I can use instanceof (and in most cases this is what I'm doing) but there are few scenarios where $item->getType() would make my life so much easier.

8条回答
叼着烟拽天下
2楼-- · 2019-01-08 19:35

There's a slicker way to do it in PHP 5.3:

abstract Parent
{
    const TYPE = 'Parent';

    public static function get_type()
    {
        $c = get_called_class();
        return $c::TYPE;
    }
}

class Child_1 extends Parent
{
    const TYPE = 'Child Type #1';
    //..whatever
}

class Child_2 extends Parent
{
    const TYPE = 'Child Type #2';
    //...whatever
}
查看更多
狗以群分
3楼-- · 2019-01-08 19:36

My approach is to simply access it's value through the meta data doctrine generates

$cmf = $em->getMetadataFactory();
$meta = $cmf->getMetadataFor($class);
$meta->discriminatorValue

will give you the value, so as a method

public static function get_type()
{
    //...get the $em instance 
    $cmf = $em->getMetadataFactory();
    $meta = $cmf->getMetadataFor(__CLASS__);
    return $meta->discriminatorValue;
}

I cache the metadata in a static variable for each class that extends my base entity, there is a lot of other useful information in there as well ...

查看更多
登录 后发表回答