if (Drupal::hasService('database')) { // Code to be executed if the database service exists } else { // Code to be executed if the database service does not exist }
if (Drupal::hasService('my_module.my_service')) { // Code to be executed if the my_module.my_service service exists } else { // Code to be executed if the my_module.my_service service does not exist }This example checks if a custom module's service named `my_module.my_service` exists in the application. If it exists, the code within the `if` block will be executed. If not, the code within the `else` block will be executed. Package Library: Drupal\Core\DependencyInjection\Container