In this article, we are going to learn when to use hook_update_N
and hook_post_update_NAME
. In general, I was using hook_update_N
for any database-related changes or with any configuration additions or updates. And I was using hook_post_update_NAME
for any content creation or updating or for the creation or updating any taxonomy terms etc, sometimes for clearing site caches as well.
But, let’s have a check like why Drupal is offering us these two features and what is the flow of execution of these two.
I have checked few core modules and a few contributed modules and understood that In a few of the modules there is no clear separation in the usage of these two hooks and in a few of the modules hook_update_N
is used to modify field definitions and hook_post_update_NAME
is used for creating or updating data.
I have gone through a few of the articles and documentations and understood that within hook_update_N
it's better to do config or database related changes & in the hook_post_update_NAME
it's better to do entity changes or content changes or something else.
To get to know more about about, had a check in the drupal core code and found the DbUpdateController
class, in which triggerBatch
method is doing the stuff on running https://drupal.local/update.php
- Initially all
hook_update_N
are found here and on the basis of module name they are picked up into the batch. - Later
hook_post_update_NAME
are found and added to the batch. In case if any exist then all the caches are flushed at this point.
Also check the Drush, to understand how drush triggers this stuff. And UpdateDBCommands
is the class, in which updateBatch
method is doing the stuff on running drush updb
.
- Initially gets all the
hook_update_N
and sorts on the basis of module name and adds to the batch to process and flush caches. - In case if any
hook_post_update_NAME
exists, add allhook_post_update_NAME
to the batch to process.
Small difference on running update.php
and drush updb
, its flushing caches during the process, apart from this else is the same.
Overall, it's not clear which one to use for what actions. And I see, better would be using hook_update_N
for doing database changes or configuration changes and using hook_post_update_NAME
for doing any entity changes or content changes. Let me know your thoughts in the comments.