[8.x] Allow running observer callbacks after database transactions have committed #440
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR re-implements #436 but makes it configurable. I added
$afterCommit
to Scout'sModelObserver
again, but this time instead of setting it totrue
I set it based on a new config file entry calledafter_commit
.Since this PR defaults these values to
false
, this approach is completely backwards-compatible with all existing Scout installs, in application and test code. I'm targeting the8.x
branch so that apps that need it can start using this functionality immediately, and I'll submit another PR tomaster
to turn it on by default in the next major version of Scout.Closes #437.
Alternatives
I'm sure there are other ways to tackle this, and I'm happy to explore them, but this seemed like the simplest by far. Two other ideas I played with briefly:
afterCommit
method to theModelObserver
, and updating Laravel's event dispatcher to look for that method and allow it to override the property when present. This pattern feels familiar to me, in line with things like theshouldDiscoverEvents
method in theEventServiceProvider
, but it could get confusing because in other places (queue-related) there areafterCommit
methods that explicitly set it totrue
and don't allow the logic to be customized. This approach would also still require a config option, because users still wouldn't be able to override the method.$afterCommit
static, which would allow it to be overridden globally for a specific listener/observer, for example in a service provider or base test case. This is powerful and simple but feels hacky.