Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 + Doctrine 2 overriding entity configuration

I have a case where I need to reuse common doctrine entities across multiple applications (that reside within the same project). These applications are merely instances of information system used by corresponding institutions.

I've isolated all entities and repositories into separate bundle and that worked like a charm so far. Here's the catch: I have received a requirement that only some of these instances need to support some other features. Modification would include adding new attributed/relations to some of entities.

Here is the brief example:

We have a university which has number of faculty units (instances, that is). Information system was built to support only bachelor studies program but a month ago we received requirement to support specialization and master studies as well. They want to handle all the them thought the same application instance. This applies only to some of these instances.

The question: Is there any way to "override" affected entities while keeping functionality of original ones? Can I override entity configuration (YAML or annotation, not important), at all? I would really like to keep the code base and not to copy all the entities/repositories to another package...

like image 880
Jovan Perovic Avatar asked Feb 19 '23 20:02

Jovan Perovic


2 Answers

You can override classes metadata on entities loading by catching an event.

EventListener

<?php

namespace Lol\RandomBundle\EventListener;

use Doctrine\ORM\Event\LoadClassMetadataEventArgs;

class ClassMetadataListener
{
    /**
     * Run when Doctrine ORM metadata is loaded.
     *
     * @param LoadClassMetadataEventArgs $eventArgs
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $classMetadata = $eventArgs->getClassMetadata();

        // Override User class to flag MappedSuperclass.
        if ('AnotherLol\AnotherRandomBundle\Entity\User' === $classMetadata->name) {
            // Do whatever you want...
            $classMetadata->isMappedSuperclass = true;
        }
    }
}

Services configuration

services:
    lol.random.listener.class_metadata:
        class: Lol\RandomBundle\EventListener\ClassMetadataListener
        tags:
            -  { name: doctrine.event_listener, event: loadClassMetadata }
like image 147
Aistis Avatar answered Feb 27 '23 11:02

Aistis


Sympatch provides tools to override any code part of your Symfony2 project, including entities, without destroying the code base. See https://github.com/DHorchler/SympatchBundle.

like image 44
D.H. Avatar answered Feb 27 '23 11:02

D.H.