You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide the ability to use existing entities in commands for cascading persistence of state aggregate. #307
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.
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.
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
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.
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.
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.
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
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.
In Ecotone Framework, the ObjectManagerInterceptor clears the Doctrine EntityManager before proceeding with the method invocation. This causes problems when working with Doctrine ORM.
Now, Ecotone can detect that this command should not clear the EntityManager.
Modify ObjectManagerInterceptor
Instead of checking metadata, check whether the command implements PreventEntityManagerClear:
privatefunctionshouldSkipClearing(MethodInvocation$methodInvocation): bool
{
$arguments = $methodInvocation->getArguments();
if (empty($arguments)) {
returnfalse;
}
$command = $arguments[0]; // The first argument is the command or event objectreturn$commandinstanceof 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.
if ($this->depthCount === 1) {
$this->clearAggregatesOnly($objectManager);
}
privatefunctionclearAggregatesOnly(EntityManagerInterface$entityManager): void
{
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getIdentityMap() as$className => $entities) {
$reflectionClass = new \ReflectionClass($className);
// Check if the class has the #[Aggregate] attributeif (!empty($reflectionClass->getAttributes(Aggregate::class))) {
foreach ($entitiesas$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.
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.
@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.
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).
@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.
Activity
lifinsky commentedon Mar 27, 2024
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.
dgafka commentedon Mar 28, 2024
Can you provide PR with failing scenario?
lifinsky commentedon Mar 28, 2024
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
lifinsky commentedon Mar 28, 2024
@dgafka https://gist.github.com/sushchyk/8ce3c718270f0ac75eb07264f899722a
dgafka commentedon Mar 29, 2024
So the case is that when we've main Entity (Aggregate Root) like
Postand we change it's child EntitiesTag, 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?
lifinsky commentedon Mar 29, 2024
No, existing tag was saved but as new record (doctrine allows cascade: ['persist']):
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.
lifinsky commentedon Mar 29, 2024
Currently for this example we should find tag in interceptor with pointcut "before" on CommandHandler (after transaction start)
dgafka commentedon Mar 30, 2024
So the problem is that we create
TagEntity before outside ofPostAggregate.As Post Aggregate is created via Command, Unity of Work is cleared, therefore the reference to
Tagis also cleared.This makes Doctrine ORM think this is new Entity, which need to be inserted instead of updated.
@lifinsky is this understanding correct?
lifinsky commentedon Mar 30, 2024
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
dgafka commentedon Mar 30, 2024
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.
benr77 commentedon Jul 30, 2024
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
lifinsky commentedon Jul 30, 2024
This issue is actual and not resolved
lifinsky commentedon Feb 8, 2025
In Ecotone Framework, the ObjectManagerInterceptor clears the Doctrine EntityManager before proceeding with the method invocation. This causes problems when working with Doctrine ORM.
ecotone-dev/packages/Dbal/src/ObjectManager/ObjectManagerInterceptor.php
Line 54 in 601142d
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
Create a PreventEntityManagerClear interface.
Implement the interface in commands that should not trigger clear().
Modify ObjectManagerInterceptor to check for the interface before clearing EntityManager.
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.
Add the interface to commands that should bypass clear():
Now, Ecotone can detect that this command should not clear the EntityManager.
Instead of checking metadata, check whether the command implements PreventEntityManagerClear:
Now, modify the condition before calling 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.
lifinsky commentedon Feb 8, 2025
Attribute name options:
In general, it is always possible to avoid clearing unless inside a consumer, for example...
lifinsky commentedon Feb 8, 2025
Possible solution but maybe poor performance:
lifinsky commentedon Feb 8, 2025
Possible solution but maybe poor performance:
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.
dgafka commentedon Feb 8, 2025
I am still not sure about the problem itself.
Can you provide PR with failure test scenario?
lifinsky commentedon Feb 8, 2025
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.
dgafka commentedon Feb 8, 2025
@lifinsky so you're sending command inside command, where second one contains of an Entity (passed from execution of the first one)?
lifinsky commentedon Feb 8, 2025
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.
dgafka commentedon Feb 8, 2025
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).
lifinsky commentedon Feb 8, 2025
@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.