@@ -180,6 +180,31 @@ This is useful for side effects that should only happen after committed data is
180180visible, such as dispatching a queued job or sending a notification, and for
181181cleanup that should only happen after a real rollback.
182182
183+ Deferring Side Effects
184+ ----------------------
185+
186+ Code that changes external state should usually not run in the middle of a
187+ transaction. If the transaction rolls back after the side effect has already
188+ run, the application may send a notification for data that was never saved,
189+ invalidate a cache for a write that did not persist, or start background work
190+ that cannot find the committed row it expects.
191+
192+ Register those side effects with ``afterCommit() `` instead:
193+
194+ .. literalinclude :: transactions/013.php
195+
196+ Use ``afterRollback() `` for cleanup that should happen only when the transaction
197+ does not commit, such as removing a temporary file created before the database
198+ write:
199+
200+ .. literalinclude :: transactions/014.php
201+
202+ Model callbacks such as ``afterInsert `` and ``afterUpdate `` run after the Model
203+ query has executed, but not necessarily after the surrounding transaction has
204+ committed. If a Model callback needs to run a side effect only after commit, it
205+ should register that work with the database connection's ``afterCommit() ``
206+ method while an active transaction is already open.
207+
183208Callbacks run after the database transaction has already committed or rolled
184209back. If a callback throws an exception, that exception bubbles to the caller,
185210but the transaction outcome is not changed.
0 commit comments