Score:-1

How to create a custom example module?

cn flag

I want to create a custom module in minimum, i.e. a module which can be installed but generally doesn't do anything just for the sake of understanding how are custom modules get created after some hard time with the documentation.

example.info.yml

name: example
type: module
core_version_requirement: ^8 || ^9
description: 'example'

example.php

<?php
?>

Assuming that this is the way to go and nothing essential is missing, how is the connection between the two files is done (shouldn't I notify example.info.yml about example.php)?

leymannx avatar
ne flag
Minimum is just an info file.
Score:-1
cn flag

How the files are connected

Drupal will automatically execute the PHP file with the module name and the extension .module; this is a special case.

So, you need to rename example.php to example.module.

If you want to add additional PHP files that are not classes, you will need to include them.

For example, if I add a file example.mail.php, and I want to include that, I need to include it in example.module like this:

include_once 'example.mail.inc';

But I do not need to include example.module because it is a special case. example.module will always be executed if it exists.

Verifying example.module is included

You can use the Devel module with kint to debug Drupal, and this is a relatively easy way to check if a file is being included.

If you enable the Devel module, add the following code to example.php, and then rebuild the cache, Drupal will use kint to print the form ID on every page that includes a form.

function example_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  kint($form_id);
}
Kevin avatar
in flag
You wouldn't really do includes or require statements, they'd be classes/services callable or injectable anywhere within Drupal. The filename for hooks should also end in .module.
cn flag
@Kevin Whoops, good point about the filename. I personally use includes to keep various types of hooks separate; I added a note to make that more clear.
4uk4 avatar
cn flag
In Drupal 8/9 PHP files are in the src/ directory where they are discovered by the [autoloader](https://www.drupal.org/docs/develop/standards/psr-4-namespaces-and-autoloading-in-drupal-8). There are some specific PHP files which Drupal includes bypassing the autoloader like this .module file.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.