Symfony2 -> Doctrine2 : Twin Tables sharing same Entity [possible solution]


Currently: It is not possible to map several equally looking tables onto one entity. 

I have many tables that are a clone of one basic template table, and i wanted to use Doctrine2 to map thouse tables to the same entity. I’m still working on a way to do this but i came up with this possible solution ( very early to tell ).

This modification is made on the BasicEntityPersister class. The idea i have is to use the annotations to tell Doctrine when to use the TableName from the class and then to ASK the Entity for the table name to use.

We could say, as a convention, that each Entity should have a property called “__tableName” and that if the annotation for that Entity says “@ORM\Table(name=’__tableName’)” or something like that, then Doctrine should consult the entity´s property to get the class name.

Basic example ( Not tested ):

# BasicEntityPersister.php MODIFICATION
    public function executeInserts()
    {
        if ( ! $this->_queuedInserts) {
            return;
        }

        $postInsertIds = array();
        $idGen = $this->_class->idGenerator;
        $isPostInsertId = $idGen->isPostInsertGenerator();
        $sql =$this->_getInsertSQL();
        $dummy = $this->_conn->prepare($sql);
        $stmt= $dummy; //<----- Holder to when we use our custom Statement
        $tableName = $this->_class->table['name'];

        foreach ($this->_queuedInserts as $entity) {
            $insertData = $this->_prepareInsertData($entity);

            $stmt = $dummy;

            if( $tableName == '__tableName') //<- IF annotation says @ORM\Table(name='__tableName')
            {
                // Use custom Table Name! Which can be set on a PER OBJECT basis on runtime!
                $stmt =  $this->_conn->prepare( str_replace("__tableName",$entity->__tableName ,$sql) );
            }

... etc, the rest of the class.
Advertisements