Modules are how you extend Drupal. Whenever a project needs behaviour that core and contributed modules do not provide (a custom integration, a business rule, a new page, block or form), you write a custom module. This guide walks PHP developers through Drupal module development for Drupal 10 and 11: the file structure, routes and controllers, services and dependency injection, hooks, forms, configuration, permissions, testing and the practices that keep custom code maintainable.
What is a Drupal module?
A module is a package of PHP code, YAML configuration and assets that adds or changes functionality. Drupal has three kinds:
- Core modules ship with Drupal (Node, User, Views and others).
- Contributed modules are shared by the community on drupal.org.
- Custom modules are written for one project and live in
web/modules/custom.
Before writing a custom module, check drupal.org: a maintained contributed module is usually cheaper to own than custom code.
Set up your development environment
- PHP 8.3 (the recommended version for current Drupal releases) and Composer.
- A local environment such as DDEV or Lando, which provides the web server, database and Drush.
- Drush for clearing caches, enabling modules and running updates.
- Xdebug for step debugging, and the Devel module during development.
Create a project with composer create-project drupal/recommended-project my_site, then place custom modules under web/modules/custom/.
Module file structure
A typical module called hello_world looks like this:
web/modules/custom/hello_world/
├── hello_world.info.yml # module definition (required)
├── hello_world.routing.yml # URLs and their controllers
├── hello_world.services.yml # services for dependency injection
├── hello_world.permissions.yml # custom permissions
├── hello_world.module # procedural hooks (optional)
├── config/
│ ├── install/ # default configuration
│ └── schema/ # configuration schema
├── src/
│ ├── Controller/
│ ├── Form/
│ ├── Hook/ # object-oriented hooks (Drupal 11.1+)
│ └── Plugin/Block/
└── tests/src/
Drupal uses PSR-4 autoloading: classes in src/ use the namespace Drupal\hello_world.
Step 1: define the module
hello_world.info.yml tells Drupal the module exists:
name: 'Hello World'
type: module
description: 'Example custom module.'
package: Custom
core_version_requirement: ^10 || ^11
dependencies:
- drupal:node
Step 2: add a route and a controller
hello_world.routing.yml:
hello_world.page:
path: '/hello'
defaults:
_controller: '\Drupal\hello_world\Controller\HelloController::page'
_title: 'Hello'
requirements:
_permission: 'access content'
src/Controller/HelloController.php:
namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;
class HelloController extends ControllerBase {
public function page(): array {
return [
'#markup' => $this->t('Hello, @name!', ['@name' => $this->currentUser()->getDisplayName()]),
'#cache' => ['contexts' => ['user']],
];
}
}
Controllers return render arrays, not HTML strings. Note the #cache context: because the output depends on the user, Drupal must cache it per user.
Free resource
Upgrade and patching checklist
Want this applied to your project? Our engineers will send it with notes for your stack.
Step 3: enable the module
drush en hello_world -y
drush cr
Visit /hello to see the page.
Step 4: use services and dependency injection
Put business logic in services instead of controllers or hooks. Define one in hello_world.services.yml:
services:
hello_world.greeter:
class: Drupal\hello_world\Greeter
arguments: ['@config.factory', '@logger.factory']
Then inject it into the controller through create() (or use autowiring in recent Drupal versions):
use Drupal\hello_world\Greeter;
use Symfony\Component\DependencyInjection\ContainerInterface;
public function __construct(private readonly Greeter $greeter) {}
public static function create(ContainerInterface $container): static {
return new static($container->get('hello_world.greeter'));
}
Avoid calling \Drupal::service() inside classes; injected services are easier to test and reuse.
Step 5: react to events with hooks
Hooks let your module change Drupal’s behaviour. In Drupal 11.1 and later you can write hooks as class methods with the #[Hook] attribute:
namespace Drupal\hello_world\Hook;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\node\NodeInterface;
class NodeHooks {
#[Hook('node_presave')]
public function nodePresave(NodeInterface $node): void {
if ($node->bundle() === 'article' && $node->get('field_summary')->isEmpty()) {
$node->set('field_summary', 'Summary pending');
}
}
}
On Drupal 10, implement the same hook as a function in hello_world.module, for example function hello_world_node_presave(NodeInterface $node) { ... }. Common hooks include hook_form_alter, hook_entity_presave, hook_theme and hook_cron.
Step 6: build a configuration form
Configuration forms extend ConfigFormBase and store settings in configuration that can be exported and deployed between environments:
namespace Drupal\hello_world\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
class SettingsForm extends ConfigFormBase {
protected function getEditableConfigNames(): array {
return ['hello_world.settings'];
}
public function getFormId(): string {
return 'hello_world_settings';
}
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['greeting'] = [
'#type' => 'textfield',
'#title' => $this->t('Greeting'),
'#default_value' => $this->config('hello_world.settings')->get('greeting'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('hello_world.settings')
->set('greeting', $form_state->getValue('greeting'))
->save();
parent::submitForm($form, $form_state);
}
}
Provide defaults in config/install/hello_world.settings.yml and a schema in config/schema/hello_world.schema.yml so the configuration is validated and translatable.
Step 7: add permissions
hello_world.permissions.yml:
administer hello world:
title: 'Administer Hello World'
restrict access: true
Use the permission in routes (_permission: 'administer hello world') instead of checking roles in code.
Plugins, blocks and events
- Plugins are Drupal’s way to provide swappable components: blocks, field formatters and widgets, Views handlers and more. A custom block is a class in
src/Plugin/Blockwith a#[Block]attribute (or an annotation on older versions). - Event subscribers react to Symfony and Drupal events, such as redirecting requests or acting on configuration changes.
- Queue workers process slow tasks in the background, for example syncing records with an external API on cron.
Testing your module
Drupal uses PHPUnit with several test types:
- Unit tests for isolated PHP classes such as services.
- Kernel tests for code that needs a minimal Drupal bootstrap and database.
- Functional tests for full requests, permissions and forms.
Run them with vendor/bin/phpunit -c web/core web/modules/custom/hello_world. Add PHPStan with the Drupal extension and PHP_CodeSniffer with the Drupal coding standard to catch problems early.
Best practices for custom Drupal modules
- Keep business logic in services, and keep controllers, hooks and forms thin.
- Use render arrays and cache metadata (tags, contexts, max-age) correctly so pages stay fast.
- Store settings in configuration, not in code or the State API, when they should be deployable.
- Use the Entity API and Database API with placeholders, never string-built SQL.
- Translate user-facing strings with
$this->t()and sanitise output through the render system. - Follow Drupal coding standards and declare
core_version_requirementhonestly. - Write update hooks (
hook_update_N) when you change data structures in an existing module.
Upgrading modules from Drupal 7, 9 or 10
Drupal 7 reached end of life in January 2025, and its modules cannot be reused directly because the architecture changed. Rebuild them on the modern APIs and migrate content with the Migrate API. For Drupal 9 or 10 modules moving to Drupal 11, run Upgrade Status and Drupal Rector to find and fix deprecated code, then update core_version_requirement.
Frequently asked questions
What do I need to know to develop a Drupal module? Modern PHP (object-oriented programming, namespaces, Composer), basic Symfony concepts such as services and events, YAML, and Drupal’s render and entity APIs.
What is the difference between a module and a theme in Drupal? Modules add functionality and data handling; themes control presentation. Keep business logic out of themes.
How do I create a custom block in Drupal? Create a block plugin class in src/Plugin/Block that extends BlockBase and returns a render array from build(), then place it in the Block layout.
Can a module support Drupal 10 and 11 at the same time? Yes. Set core_version_requirement: ^10 || ^11 and avoid APIs deprecated in Drupal 10.
How do I debug a Drupal module? Use Xdebug, drush watchdog:show for logs, the Devel module and drush cr after changing YAML or service definitions.
Need Drupal development help?
Vibidsoft builds custom Drupal modules, integrations and Drupal 7 to Drupal 10/11 migrations. See our CMS development services and PHP development, or contact us to discuss your Drupal project.
