Jonathan
Jonathan

Reputation: 15432

Calling Doctrine clear() with an argument is deprecated

Doctrine advises that -

Calling Doctrine\ORM\EntityManager::clear() with any arguments to clear specific entities is deprecated since doctrine/persistence 1.3 and will be removed in 2.0.

We have a lot of references to ->clear(SpecificEntity::class) in our Symfony codebase and are looking to update these, but we're struggling to find a suggested replacement in the latest upgrade guide.

Is there a recommended alternative to clear a specific entity in the latest version of Doctrine?

Upvotes: 5

Views: 5407

Answers (1)

dbrumann
dbrumann

Reputation: 17166

Calling clear($entity) has some side effects and unclear behavior, e.g. what happens to relationships in/to that entity? The idea is, that your unit of work (in-memory changes that Doctrine keeps track of until you hit flush) should be small and only contain entities that you want to change, to avoid uncertainties of what is being saved/cleared. Instead of taking out the entity it should not be in there in the first place. Instead it could for example get it's own flush-"cycle" followed by a clear of the entire unit of work to show that those changes are independent from the other ones.

There are multiple ways to do this, most commonly (I think) are:

Use clear() (without specific entity) more often.

This likely requires you to ensure that all changes to entities are closely grouped together to make sure there are no accidental writes on other entities. You likely will also have to re-read data more often. In order to offset this, you should use the second level cache.

Using a different change tracking policy

By default all changes are implicitly tracked and then persisted. Instead you can tell Doctrine to only write explicit changes. What this means is, when for example you have a User with many addresses and you only call persist($user), then associated address changes will not be saved. Instead you manually have to call persist on each address that should be saved. You don't have to call clear as often, because you explicitly say which entity-changes should be persisted.


Both options require you to reorganize your business logic, which makes it really hard to give a general upgrade guide for this. Generally speaking, the reasons and solutions are quite similar to what is described for flush($entity), which got it's section in the docs: https://github.com/doctrine/orm/blob/master/UPGRADE.md#bc-break-removed-entitymanagerflushentity-and-entitymanagerflushentities

Upvotes: 6

Related Questions