Update hooks
Update hooks automate database schema changes, data migrations, and environment-specific deployment tasks, so a change ships together with the code that needs it instead of being applied by hand.
Drupal provides several types of hooks for database updates. Understanding the differences helps you choose the right one for a deployment task.
Hook types overview
| Hook type | Use case | Execution | File location |
|---|---|---|---|
hook_update_N() | Database schema changes, data migrations | drush updatedb | MODULE.install |
hook_post_update_NAME() | Entity updates and other module operations | drush updatedb | MODULE.post_update.php |
hook_deploy_NAME() | Environment-specific deployment tasks | drush deploy:hook | MODULE.deploy.php |
All of these hooks run automatically during the
provisioning process: drush updatedb runs the update and
post-update hooks, and drush deploy:hook runs the deploy hooks.
To automate changes during site deployments, use deploy hooks. Note that deploy hooks run only once: Drupal tracks which hooks have been executed by name.
Example deploy hook
function ys_base_deploy_create_about_page(): string {
$environment = \Drupal\Core\Site\Settings::get('environment');
// Conditional execution based on environment.
if ($environment === ENVIRONMENT_PROD) {
return 'Skipped in production environment';
}
// Check if the About Us page already exists.
$node = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'page']);
if (!empty($node)) {
return 'About Us page already exists';
}
$node = \Drupal\node\Entity\Node::create([
'type' => 'page',
'title' => 'About Us',
'body' => [
'value' => 'This is the About Us page content.',
'format' => 'basic_html',
],
]);
$node->save();
return 'Created About Us page';
}
Debugging commands
# Show pending deploy hooks.
drush deploy:hook-status
# Run deploy hooks manually (for testing).
drush deploy:hook