A custom controller in Drupal is a user-defined PHP class that acts as a middleman between user requests and the final response displayed on the website. It essentially controls how your custom functionality works in Drupal. Here's a breakdown of what custom controllers do:
Begin by creating a new directory for your module within the modules/custom directory of your Drupal installation. Let's name it my_module.
Inside the my_module directory, create the following files:
Step 2: Define Module Information
Create the file my_module.info.yml with the following content:
name: 'My Module'
type: module
description: 'A custom module to demonstrate Drupal controller functionality.'
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
- drupal:system
In this file, you specify the name, description, and dependencies of your module.
Step 3: Define Routes
Next, create the file my_module.routing.yml and add the following content:
my_module.greeting:
path: '/my-module/greeting'
defaults:
_controller: '\Drupal\my_module\Controller\MyController::greeting'
_title: 'My Module Greeting'
requirements:
_permission: 'access content'
This file defines a route for your module. It specifies the path, controller method to call, and the required permission to access the page.
Step 4: Create the Controller
Inside the my_module/src/Controller directory, create the file MyController.php. Then, add the following code:
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
class MyController extends ControllerBase {
public function greeting() {
return ['markup',
'#markup' => $this->t('Hello, world! This is my first Drupal controller.'),
];
}
}
This controller class contains a method called greeting() which returns a greeting message.
Step 5: Enable the Module
Navigate to the Extend page (/admin/modules) on your Drupal site and enable the "My Module" module.
Step 6: Test the Controller
Finally, visit http://your-drupal-site.com/my-module/greeting in your web browser. You should see the greeting message displayed on the page.
Congratulations! You've successfully created a custom module with a controller in Drupal, allowing you to add custom functionality to your website. Feel free to expand upon this module by adding more controllers, services, or other features as needed.