How to Work with Lifecycle Callbacks
How to Work with Lifecycle Callbacks¶
Sometimes, you need to perform an action right before or after an entity is inserted, updated, or deleted. These types of actions are known as "lifecycle" callbacks, as they're callback methods that you need to execute during different stages of the lifecycle of an entity (e.g. the entity is inserted, updated, deleted, etc).
If you're using annotations for your metadata, start by enabling the lifecycle callbacks. This is not necessary if you're using YAML or XML for your mapping.
1 2 3 4 5 6 7 8 | /**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Product
{
// ...
}
|
Now, you can tell Doctrine to execute a method on any of the available lifecycle
events. For example, suppose you want to set a createdAt
date column to
the current date, only when the entity is first persisted (i.e. inserted):
- Annotations
1 2 3 4 5 6 7 8 9
// src/AppBundle/Entity/Product.php /** * @ORM\PrePersist */ public function setCreatedAtValue() { $this->createdAt = new \DateTime(); }
- YAML
1 2 3 4 5 6
# src/AppBundle/Resources/config/doctrine/Product.orm.yml AppBundle\Entity\Product: type: entity # ... lifecycleCallbacks: prePersist: [setCreatedAtValue]
- XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<!-- src/AppBundle/Resources/config/doctrine/Product.orm.xml --> <?xml version="1.0" encoding="UTF-8" ?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="AppBundle\Entity\Product"> <!-- ... --> <lifecycle-callbacks> <lifecycle-callback type="prePersist" method="setCreatedAtValue" /> </lifecycle-callbacks> </entity> </doctrine-mapping>
Note
The above example assumes that you've created and mapped a createdAt
property (not shown here).
Now, right before the entity is first persisted, Doctrine will automatically
call this method and the createdAt
field will be set to the current date.
There are several other lifecycle events that you can hook into. For more information on other lifecycle events and lifecycle callbacks in general, see Doctrine's Lifecycle Events documentation.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.