Drupal Best Practices: The Importance of Documentation for Sustainable Development

Good documentation is an essential part of any Drupal project. It ensures that both developers and site administrators understand how a site works, how it’s structured, and how to maintain it effectively. Whether you’re building a small custom module or managing a complex multi-site Drupal installation, clear and comprehensive documentation saves time, reduces errors, and ensures smooth handovers to other developers or administrators.

In this blog post, we’ll cover two crucial aspects of Drupal documentation:

  1. Code Documentation: Following PHPDoc standards to document all custom functions, classes, and methods.
  2. Site Documentation: Maintaining clear, user-friendly documentation for site structure, content types, and custom features to facilitate handovers and ongoing maintenance.

By adhering to these documentation best practices, you’ll create a more maintainable, understandable, and future-proof Drupal site that can be easily handed over and worked on by others.


1. Code Documentation: Using PHPDoc for Clear, Consistent Code

When building custom modules or themes for Drupal, properly documenting your code using PHPDoc is essential. PHPDoc is a widely accepted standard for documenting PHP code, and it provides a structured way to describe the purpose and behavior of functions, methods, and classes.

Why Code Documentation is Important

  1. Improve Code Readability: Well-documented code is easier to understand, both for the original developer and for anyone who works on the project later. Proper documentation explains why a particular function exists, what it does, and how it should be used.
  2. Facilitate Collaboration: In collaborative environments, where multiple developers work on the same project, clear documentation prevents confusion and reduces the risk of errors. It helps developers quickly understand how the code works and how different components interact.
  3. Simplify Maintenance: As the project evolves, code documentation becomes a valuable resource for maintaining and updating the codebase. Well-documented functions and methods make it easier to refactor or update code without breaking functionality.
  4. Integration with IDEs: Most modern integrated development environments (IDEs) support PHPDoc comments and will display the comments as tooltips when hovering over functions or methods. This makes it easier for developers to quickly see what a function does without needing to search through the code.

PHPDoc Standards for Drupal

When documenting Drupal code, it’s important to follow PHPDoc standards. Each function, method, class, and file should have a clear, descriptive comment block that explains its purpose, parameters, return values, and any exceptions.

Example of a Well-Documented Function

Here’s an example of how to properly document a custom function in a Drupal module using PHPDoc:

/**
 * Retrieves a list of upcoming events for the specified user.
 *
 * This function fetches events from the database that are assigned to the
 * given user and are scheduled for a future date.
 *
 * @param int $uid
 *   The user ID for whom to retrieve events.
 * @param int $limit
 *   (Optional) The number of events to retrieve. Defaults to 10.
 *
 * @return array
 *   An array of event objects, each containing the event title, date, and ID.
 *
 * @throws \Exception
 *   Throws an exception if the database query fails.
 */
function mymodule_get_upcoming_events($uid, $limit = 10) {
  $query = \Drupal::database()->select('events', 'e')
    ->fields('e', ['id', 'title', 'event_date'])
    ->condition('e.uid', $uid)
    ->condition('e.event_date', strtotime('now'), '>')
    ->range(0, $limit)
    ->execute();

  if (!$query) {
    throw new \Exception('Failed to retrieve events.');
  }

  return $query->fetchAll();
}

Key Elements of PHPDoc:

  1. Short Description: A brief summary of what the function does.
  2. Detailed Description: An explanation of how the function works and any important details.
  3. Parameters (@param): For each parameter, specify the data type and a short description of its purpose.
  4. Return (@return): Specify the return type and describe the structure of the returned data.
  5. Exceptions (@throws): If the function throws an exception, specify what kind of exception and under what circumstances it occurs.

Documenting Classes and Methods

If you’re working with object-oriented programming (OOP) in Drupal, you should also document your classes and methods. Here’s an example of how to document a class:

/**
 * Provides a custom event manager service.
 *
 * This service handles the creation, updating, and deletion of event nodes.
 */
class EventManager {

  /**
   * Creates a new event node.
   *
   * @param string $title
   *   The title of the event.
   * @param int $date
   *   The event date as a Unix timestamp.
   *
   * @return \Drupal\node\NodeInterface
   *   The newly created event node.
   */
  public function createEvent($title, $date) {
    $node = \Drupal\node\Entity\Node::create([
      'type' => 'event',
      'title' => $title,
      'field_event_date' => $date,
    ]);
    $node->save();

    return $node;
  }
}

Best Practices for Code Documentation

  1. Document Every Custom Function and Class: Every function, method, and class in your custom module or theme should be documented, even if it seems simple or self-explanatory.
  2. Update Documentation Regularly: As your code evolves, make sure to update the corresponding documentation. Outdated or incorrect documentation can be misleading and cause more harm than good.
  3. Be Concise but Descriptive: You don’t need to document every single line of code, but make sure that the purpose of each function or method is clear and understandable. Describe what the function does, not how it does it (the code itself should explain that).

2. Site Documentation: Clear Documentation for Administrators and Developers

Beyond documenting the code, it’s essential to maintain clear, user-friendly documentation for the site structure, content types, and any custom features. This documentation is particularly important when handing over the project to other developers or site administrators who may need to maintain or extend the site in the future.

Why Site Documentation is Important

  1. Ease of Handover: Clear site documentation ensures that other developers, administrators, or content editors can easily understand how the site is built and how to manage it. This is critical for long-term site maintenance and development, especially when new team members join or when the original developers are no longer available.
  2. Reduces Errors: Without proper documentation, developers or administrators may inadvertently make changes that break the site or conflict with existing functionality. Good documentation helps prevent these errors by providing clear instructions on how to use and manage the site.
  3. Facilitates Custom Feature Usage: Custom content types, views, and features can be difficult to understand without documentation. Describing how to use these features ensures that administrators and content editors can fully utilize the site’s capabilities.

What to Include in Site Documentation

  1. Site Structure: Document the overall site structure, including navigation menus, page layouts, and any custom blocks or regions. Provide a high-level overview of how the site is organized.
  2. Content Types: For each custom content type, include a description of the content type’s purpose and explain its fields, relationships, and any specific workflows. For example, document how the “Event” content type works, including which fields are required and how to enter event dates.
  3. Views: If your site uses Drupal’s Views module, document any custom views, including their purpose, what content they display, and any filters or sorting applied. This is especially helpful when other developers or administrators need to modify or troubleshoot views.
  4. Custom Modules and Features: Document any custom modules or features you’ve built, including what they do and how they integrate with the site. This is particularly important for complex features that may not be intuitive for new developers.
  5. Configuration: Explain how key site configurations are managed, such as caching settings, URL aliases, or multilingual settings. Include instructions for exporting or importing configurations if using Drupal’s Configuration Management system.
  6. Roles and Permissions: Document the roles and permissions structure for the site. Explain what each role can do and how permissions are managed.
  7. Third-Party Integrations: If the site integrates with third-party services (e.g., payment gateways, external APIs), provide documentation on how these integrations work and how they’re configured.

Example of a Site Documentation Section: Custom Content Type

Here’s an example of documentation for a custom “Event” content type:


Event Content Type Documentation

Description: The Event content type is used for creating events that will be displayed on the event listing page. Each event has a title, date, location, and description.

Fields:

  • Title: The name of the event.
  • Event Date: The date of the event (stored as a Unix timestamp).
  • Location: A text field for entering the event’s location.
  • Description: A rich-text field where the event details are provided.

Usage:

  • To create an event, navigate to Content → Add Content → Event.
  • Fill in the event details, including the title, date, location, and description.
  • Save the event, and it will appear on the event listing page automatically.

Views:

  • The Event Listing view is responsible for displaying upcoming events. It shows the event title, date, and location in a list format. The view filters out past events and sorts them by event date.

Best Practices for Site Documentation

  1. Make Documentation Accessible: Store your documentation in a place that’s easy for developers and administrators to access. Consider using a wiki, shared document, or a dedicated documentation section within the Drupal admin interface.
  2. Keep Documentation Updated: As the site evolves and new features are added or existing ones are modified, ensure the documentation is updated to reflect these changes.
  3. Provide Examples: Wherever possible, provide examples or screenshots to make it easier for non-technical users to understand the documentation.
  4. Tailor Documentation for Your Audience: Developers will need more technical details (like how to deploy configurations or modify custom modules), while administrators and content editors need instructions on how to manage content and configure the site.

Conclusion

Clear and thorough documentation is a cornerstone of successful Drupal development. By following PHPDoc standards for code documentation, you ensure that your custom functions, classes, and methods are easy to understand and maintain. Similarly, by creating comprehensive site documentation, you make it easier for administrators and developers to manage and maintain the site in the future.

Here’s a quick recap of the key best practices for Drupal documentation:

  1. Code Documentation: Use PHPDoc to document every custom function, class, and method. Keep documentation concise but informative, and update it regularly as the code evolves.
  2. Site Documentation: Maintain clear, accessible documentation for the site’s structure, content types, custom features, and configurations. Tailor this documentation for both developers and administrators.

By following these documentation practices, you’ll ensure that your Drupal site is easier to manage, maintain, and scale, helping future developers and administrators take over with confidence.

Do you agree with the content of this article?

You need to join to the Drupal COE to participate, Log In or Claim your profile now.

Did you find this useful?

Would you suggest another article for the Best Practices category?

You need to join to the Drupal COE to participate, Log In or Claim your profile now.