vendredi 15 mars 2019

Wich is the best practice in OOP's design to get a list of subclass : by reflection VS by my own list in a table?

I'm facing a situation where I need to get a list of subclass

/**
 * @ORM\Table(name="parentclass")
 * @ORM\Entity(repositoryClass="App\Repository\ParentClassRepository")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"Subclass 1" = "SubClass1", "Subclass 2" = "SubClass2"})
 */
abstract class ParentClass
{
}

From my POV there are two way I can get that list. The first one is to use doctrine's metadatas :

$this->getDoctrine()->getManager()->getClassMetadata(ParentClass::class)->discriminatorMap

Consequences are I have to use reflection :

$givenId = 'Subclass 1';
$em = $this->getDoctrine()->getManager();
$subClassName = $em->getClassMetadata(ParentClass::class)->discriminatorMap[$givenId];
$subClassInstance = (new \ReflectionClass($subClassName))->newInstance();

The second one is to implement a class SubclassType that will lead to a table :

+-------------------+
|   SubClassType    |
+------+------------+
|  ID  |    Name    |
+------+------------+
|  1   | SubClass 1 |
+------+------------+
|  2   | SubClass 2 |
+------+------------+

Consequences are I have to manage mapping by myself :

$givenId = 1;
$subClassInstance = null;
switch($givenId)
{
    case 1:
        $subClassInstance = new SubClass1();
    break;
    case 2:
        $subClassInstance = new SubClass2();
    break;
}

I apologize in advance. I tried to make my question understandable but it's hard.

I'm really interested by all reflexions, advices, counter indications, articles, topics and posts you can know about this subject.

My objectif about design is to be the most understandable, robust, easier to read and to make evolve, clear in the intention.





Aucun commentaire:

Enregistrer un commentaire