Symfony 2 + Doctrine 2 overriding entity configura

2019-05-13 21:49发布

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...

3条回答
我想做一个坏孩纸
2楼-- · 2019-05-13 21:57

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.

查看更多
在下西门庆
3楼-- · 2019-05-13 22:00

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 }
查看更多
Ridiculous、
4楼-- · 2019-05-13 22:23

I don't know what this means. Looks like it is possible but not documented yet. I don't whether the documentation or the code is in progress.

In this issue, stof suggests it is not possible at all.

I think you should use SCM branches for this.

查看更多
登录 后发表回答