Loading...

Creating a Drupal Custom Module with Controller


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:

Responsibilities:

  • Handle User Requests: When a user interacts with your custom feature (e.g., visiting a specific page or submitting a form), the custom controller receives the request.
  • Interact with the Model: The controller retrieves relevant data from the model layer, which could involve querying the database or other sources. This data might be content, user information, or anything needed to fulfill the user's request.
  • Prepare the Response: Based on the user's request and retrieved data, the controller builds a response that gets sent back to the user. This response can be:
    • HTML Pages: For displaying custom content or functionalities on the website.
    • JSON Data: For API interactions where data needs to be exchanged in a structured format.
    • Other Formats: Depending on the specific purpose of the controller.
  • Utilize Services and Libraries: Controllers often interact with other built-in Drupal services or external libraries to perform specific tasks. This could involve tasks like user authentication, sending emails, utilizing caching mechanisms, or interacting with external APIs.

Benefits of Using Custom Controllers:

  • Organized Code: Controllers promote separation of concerns by isolating request handling logic from the presentation layer (templates) and the data layer (models). This makes code more maintainable and easier to test.
  • Reusability: A single controller can be used for different parts of your website if they share similar functionalities. This reduces code duplication and improves development efficiency.
  • Testability: Unit testing controllers becomes easier as they encapsulate specific logic for handling requests, making it simpler to test their behavior in isolation.
     

Creating a Custom Controller:

Step 1: Set Up the Module Directory and Files

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:

  1. my_module.info.yml: This file provides metadata about the module.
  2. my_module.routing.yml: This file defines the routes for the module.
  3. src/Controller/MyController.php: This file contains the controller class.

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.