How to change and entity type in Doctrine2 CTI Inheritance

前端 未结 4 974
走了就别回头了
走了就别回头了 2020-12-17 18:38

How (if possible at all) do you change the entity type with Doctrine2, using it\'s Class Table Inheritance?

Let\'s say I have a Person parent class type

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 18:47

    PHP doesn't have support for object casting, so Doctrine doesn't support it. To workaround the problem I write this static method into parent classes:

    public static function castToMe($obj) {
    
        $class = get_called_class();
        $newObj = New $class();
    
        foreach (get_class_vars(get_class($newObj)) as $property => $value) {
            if (method_exists($obj, 'get' . ucfirst($property)) && method_exists($newObj, 'set' . ucfirst($property))) {
                $newObj->{'set' . ucfirst($property)}($obj->{'get' . ucfirst($property)}());
            }
        }
    
        return $newObj;
    }
    

    You can create this method in class Person and use it to cast from Employe to Client and viceversa:

    $employe = New Employe();
    $client = Client::castToMe($employe);
    

    Now, if you want, you can remove the $employe entity.

提交回复
热议问题