Skip to content

Provide the ability to use existing entities in commands for cascading persistence of state aggregate. #307

Closed

Description

@lifinsky

Description
In aggregates, it's possible to use, for instance, Doctrine entities with cascading persistence, but only for their insertion. Because ObjectManagerInterceptor clear object manager on transaction start.

Example
The only way to correctly save an aggregate with a one-to-many or many-to-many collection of entities is to inject the repository into the command handler of the aggregate or to use a "Before" interceptor that adds entities into the command before passing it to the handler.

Activity

  1. lifinsky commented on Mar 27, 2024

    @lifinsky
    ContributorAuthor

    Current possible solution:
    Add interceptor on #[Before(pointcut: CommandHandler::class)], that takes the command with an entity id, then uses the repository to find the entity and returns the same or a different command instance, but with the entity instead of the id.

  2. dgafka commented on Mar 28, 2024

    @dgafka
    Member

    Can you provide PR with failing scenario?

  3. lifinsky commented on Mar 28, 2024

    @lifinsky
    ContributorAuthor

    Hi. I will add code snippets describing the problem. After clear all existing in database entities doctrines are perceived as new and their insertion and binding occurs, instead of just binding to the aggregate

  4. lifinsky commented on Mar 28, 2024

    @lifinsky
    ContributorAuthor
  5. dgafka commented on Mar 29, 2024

    @dgafka
    Member

    So the case is that when we've main Entity (Aggregate Root) like Post and we change it's child Entities Tag, those child Entities won't be saved in database. And this is because we've not have not called ->persist(Tag) on each of them, so Doctrine does not know that they are meant to be saved.

    @lifinsky do I understand the problem correctly?

  6. lifinsky commented on Mar 29, 2024

    @lifinsky
    ContributorAuthor

    No, existing tag was saved but as new record (doctrine allows cascade: ['persist']):

    // ObjectManagerInterceptor
                foreach ($managerRegistries as $managerRegistry) {
                    /** @var EntityManagerInterface $objectManager */
                    foreach ($managerRegistry->getManagers() as $name => $objectManager) {
                        if (! $objectManager->isOpen()) {
                            $managerRegistry->resetManager($name);
                        }
                        if ($this->depthCount === 1) {
                            $objectManager->clear();
                        }
                    }
                }
    

    I think we should clear only agregates in unit of work. Entity manager supports clear($entityName = null) - null|string $entityName – if given, only entities of this type will get detached.

  7. lifinsky commented on Mar 29, 2024

    @lifinsky
    ContributorAuthor

    Currently for this example we should find tag in interceptor with pointcut "before" on CommandHandler (after transaction start)

  8. dgafka commented on Mar 30, 2024

    @dgafka
    Member

    So the problem is that we create Tag Entity before outside of Post Aggregate.
    As Post Aggregate is created via Command, Unity of Work is cleared, therefore the reference to Tag is also cleared.
    This makes Doctrine ORM think this is new Entity, which need to be inserted instead of updated.

    @lifinsky is this understanding correct?

  9. lifinsky commented on Mar 30, 2024

    @lifinsky
    ContributorAuthor

    Problem in using of existing entity, with current functionality of Ecotone we should inject tag repository to aggregate class or use command handler interceptor that find entity by id and fill attribute in command or return new command object (command is ugly with default arguments with null, for example int $tagId = null, Tag $tag = null. We should not clear entities in unit of work before command transaction

  10. dgafka commented on Mar 30, 2024

    @dgafka
    Member

    We should not clear entities in unit of work before command transaction

    I think, it's fine to set up clearing after, as long as we can clean with each Message, we are good.
    Feel free to provide a PR with a test case you mentioned.

  11. benr77 commented on Jul 30, 2024

    @benr77

    I'm running into this same issue. Did anything get sorted in the end as the last comment is quite a while ago and I can't find any related PR. Thanks

  12. lifinsky commented on Jul 30, 2024

    @lifinsky
    ContributorAuthor

    I'm running into this same issue. Did anything get sorted in the end as the last comment is quite a while ago and I can't find any related PR. Thanks

    This issue is actual and not resolved

  13. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    In Ecotone Framework, the ObjectManagerInterceptor clears the Doctrine EntityManager before proceeding with the method invocation. This causes problems when working with Doctrine ORM.

    Possible Solution

    Optionally Disabling EntityManager Clearing via Interface for command

    We can use a marker interface to specify that a command should not trigger EntityManager::clear() before execution.


    Solution Steps

    1. Create a PreventEntityManagerClear interface.

    2. Implement the interface in commands that should not trigger clear().

    3. Modify ObjectManagerInterceptor to check for the interface before clearing EntityManager.


    1. Create the Interface

    Define a simple marker interface that commands can implement to prevent EntityManager clearing:

    Interface PreventEntityManagerClear {}

    This interface does not require any methods — its presence is enough to signal behavior.


    1. Implement the Interface in Commands

    Add the interface to commands that should bypass clear():

    readonly class CreatePostCommand implements PreventEntityManagerClear
    {
        public function __construct(
            public string $title,
            public Tag $tag
        ) {}
    }

    Now, Ecotone can detect that this command should not clear the EntityManager.


    1. Modify ObjectManagerInterceptor

    Instead of checking metadata, check whether the command implements PreventEntityManagerClear:

    private function shouldSkipClearing(MethodInvocation $methodInvocation): bool
    {
        $arguments = $methodInvocation->getArguments();
    
        if (empty($arguments)) {
            return false;
        }
    
        $command = $arguments[0]; // The first argument is the command or event object
        return $command instanceof PreventEntityManagerClear;
    }

    Now, modify the condition before calling clear():

    if ($this->depthCount === 1 && !$this->shouldSkipClearing($methodInvocation)) {
        $objectManager->clear();
    }

    @dgafka We can, of course, use an additional attribute for the command handler itself to avoid adding an infrastructure interface to the domain layer where the command class is located.

  14. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    Attribute name options:

    #[PreserveEntityState]
    #[SkipEntityManagerReset]
    #[DisableEntityManagerClear]

    In general, it is always possible to avoid clearing unless inside a consumer, for example...

  15. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    Possible solution but maybe poor performance:

    // Detach only aggregates implementing AggregateRoot interface, keeping other entities managed.
    $unitOfWork = $entityManager->getUnitOfWork();
    foreach ($unitOfWork->getIdentityMap() as $className => $entities) {
        if (is_subclass_of($className, AggregateRoot::class)) {
            foreach ($entities as $entity) {
                $entityManager->detach($entity);
            }
        }
    }
  16. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    Possible solution but maybe poor performance:

    if ($this->depthCount === 1) {
        $this->clearAggregatesOnly($objectManager);
    }
    
    private function clearAggregatesOnly(EntityManagerInterface $entityManager): void
    {
        $unitOfWork = $entityManager->getUnitOfWork();
    
        foreach ($unitOfWork->getIdentityMap() as $className => $entities) {
            $reflectionClass = new \ReflectionClass($className);
            
            // Check if the class has the #[Aggregate] attribute
            if (!empty($reflectionClass->getAttributes(Aggregate::class))) {
                foreach ($entities as $entity) {
                    $entityManager->detach($entity);
                }
            }
        }
    }

    We can optimize this approach by caching which classes are aggregates to avoid unnecessary reflection calls on every transaction. Since the set of aggregates is static at runtime, we only need to check once per class and store the result.

  17. dgafka commented on Feb 8, 2025

    @dgafka
    Member

    I am still not sure about the problem itself.
    Can you provide PR with failure test scenario?

  18. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    I am still not sure about the problem itself. Can you provide PR with failure test scenario?

    Cascading saves with an aggregate, for example, entities in a many-to-many relationship that we pass directly in the command, rather than retrieving them by ID in the middle of the aggregate's command handler through an injected repository. Currently, the entity manager is cleared before the command handler is executed.

  19. dgafka commented on Feb 8, 2025

    @dgafka
    Member

    @lifinsky so you're sending command inside command, where second one contains of an Entity (passed from execution of the first one)?

  20. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    @lifinsky so you're sending command inside command, where second one contains of an Entity (passed from execution of the first one)?

    This could be an application service where these entities are retrieved by the repository and passed in the command to the aggregate. For example, tags for some state aggregate. Or places where the entity already gives the symphony its mapping for the route and so on.

    There could also theoretically be a service that calls two command handlers sequentially and can take entities saved in a cascade with the first aggregate for the second. But we don't have such a product case right now.

  21. dgafka commented on Feb 8, 2025

    @dgafka
    Member

    This could be an application service where these entities are retrieved by the repository and passed in the command to the aggregate. For example, tags for some state aggregate. Or places where the entity already gives the symphony its mapping for the route and so on.

    Is there a reason why Application Service is not being Service Command Handler? That sounds like you need more flexibility, so you could higher level and take over the orchestration process in that situation.
    It's not typicial use case to pass stateful object with stateless Commands, as it basically bind Command Handler to be run only in synchronous (as it's using unity of work started within given process).

  22. lifinsky commented on Feb 8, 2025

    @lifinsky
    ContributorAuthor

    @dgafka I am generally against having any asynchronous and distributed handlers in the domain. But I’m curious why we always have to clear the entity manager before executing a handler. It feels like there's a lack of control here.

    Perhaps we really need to introduce the concept of an Entity (with Ecotone attribute) alongside the aggregate — one that doesn’t use aggregate mechanisms and, therefore, doesn’t require clearing in the entity manager before working with the aggregate.

    We can put this discussion on hold for now, but such an approach would provide much more convenience, especially considering that Doctrine is a great solution for state aggregates.

  23. locked and limited conversation to collaborators on Feb 8, 2025
  24. converted this issue into a discussion #443 on Feb 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions