Skip to main content

Adding a new service to a custom module and the following error greeted me:

The website encountered an unexpected error. Try again later.

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "summaries.reference_node". in Drupal\Component\DependencyInjection\Container->get() (line 157 of core/lib/Drupal/Component/DependencyInjection/Container.php).

 

This issue was related to a missing the namespace declaration at the top of the PHP file.  The namespace is crucial because it tells PHP where your class is located within the overall project structure. Without it, Drupal's service container won't be able to locate and load your class, even if everything else is set up correctly.

In Drupal, namespaces are used to organise code into logical groups and to prevent name collisions between classes with the same name from different parts of a project or different projects altogether.  For modules, the namespace typically starts with Drupal\{module_name}\..., following the PSR-4 autoloading standard.  This convention allows Drupal's autoloader to find and load classes based on their file paths.

Given the ReferenceNode service class is intended to be part of the summaries module and located in the Service directory under the module's src directory, the correct namespace declaration is:

namespace Drupal\summaries\Service;

This should be placed at the very top of the ReferenceNode.php file, right before any use statements or the class definition itself.  With this namespace declaration, and assuming your service is correctly defined in your module's summaries.services.yml file, Drupal should be able to recognise and utilise your service as expected.

For context, more lines of this file

<?php

namespace Drupal\summaries\Service;

use Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityTypeManagerInterface;


class ReferenceNode {
  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new YourServiceClass object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

 

If you encounter issues like this, here are a few steps to troubleshoot:

Check the Namespace and Class Name

Ensure they match the directory structure and naming conventions expected by PSR-4.

Verify the Service Definition

Make sure the service is correctly defined in your *.services.yml file, with the correct class path.

Clear the Cache

After making changes to classes or services, always clear Drupal's cache to ensure your changes are picked up.

Review Drupal's Log

The Recent log messages (/admin/reports/dblog) can often provide additional insights into what went wrong.

Related articles