Back to Rules
PHP

Drupal 10 Module Development: PHP Best Practices, SOLID Principles & Code Examples

Claude Directory November 29, 2025
0 copies 1 downloads

Elevate your Drupal 10 modules with expert PHP guidelines, including strict typing, dependency injection, Drupal APIs, and practical code snippets for secure, performant development.

Rule Content
## Essential Guidelines for Drupal 10 Module Creation

As a seasoned Drupal 10 specialist proficient in PHP 8.1+, apply object-oriented design, SOLID methodology, and Drupal conventions to build robust, extensible modules. Focus on security, efficiency, and seamless integration using Drupal's entity system, services, and plugins.

## PHP Coding Fundamentals

Enforce strict standards for reliable code:

```php
<?php

declare(strict_types=1);

namespace Drupal\mymodule\Service;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;

class MyService {
    public function __construct(
        private readonly LoggerChannelFactoryInterface $loggerFactory,
    ) {}

    /**
     * Processes data with error handling.
     *
     * @param string $input
     * @return string
     * @throws \InvalidArgumentException
     */
    public function process(string $input): string {
        try {
            // Business logic here
            return match (true) {
                str_starts_with($input, 'valid') => 'Processed',
                default => throw new \InvalidArgumentException('Invalid input'),
            };
        } catch (\Exception $e) {
            $this->loggerFactory->get('mymodule')->error($e->getMessage());
            throw $e;
        }
    }
}
```

Always include `declare(strict_types=1);`, typed properties, match expressions, and Drupal logging.

## Drupal API Integration Best Practices

Prioritize Drupal's abstractions for data, caching, and forms:

- Opt for Database API over direct SQL.
- Apply Repository pattern for queries.
- Use service container for dependencies.

**Example Repository:**
```php
<?php

declare(strict_types=1);

namespace Drupal\mymodule\Repository;

use Drupal\Core\Database\Connection;

class MyEntityRepository {
    public function __construct(private readonly Connection $database) {}

    /**
     * Fetches entities with caching.
     */
    public function loadAll(): array {
        if ($cache = \Drupal::cache()->get('myentities')) {
            return $cache->data;
        }
        $result = $this->database->select('my_table', 't')
            ->fields('t')
            ->execute()
            ->fetchAll();
        \Drupal::cache()->set('myentities', $result, 3600);
        return $result;
    }
}
```

Leverage Queue API for async tasks and Form API for validated inputs.

## Service and Plugin Architecture

Define focused services in `mymodule.services.yml`:

```yaml
services:
  mymodule myservice:
    class: '\Drupal\\mymodule\\Service\\MyService'
    arguments: ['@logger.factory']
```

Inject via constructor for single-responsibility services.

## Controller and Routing Patterns

Keep controllers lightweight:

```php
<?php

declare(strict_types=1);

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;

final class MyController extends ControllerBase implements ContainerInjectionInterface {

  public function myPage(): array {
    $service = $this->service('mymodule.myservice');
    return [
      '#markup' => $service->process('valid data'),
    ];
  }

}
```

Routes in `mymodule.routing.yml`:

```yaml
mymodule.page:
  path: '/my-page'
  defaults:
    _controller: '\Drupal\\mymodule\\Controller\\MyController::myPage'
  requirements:
    _permission: 'access content'
```

## Documentation and Naming Standards

Use comprehensive PHPDoc and Drupal naming (e.g., `mymodule_` prefix for hooks/services).

For entities, extend base classes with annotations. Align operators in arrays:

```php
$array = [
    'key1'   => 'value1',
    'key2'   => 'value2',
];
```

Implement hooks like `hook_schema()` for tables and events for decoupling.

## Security and Configuration

Sanitize outputs, use CSRF in forms, and store settings via Config API. Translate strings with `t()`.

Follow these for scalable, maintainable Drupal 10 modules.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory