Wednesday, December 2, 2026

Drupal interview Diffination

 

In Drupal 8/9/10, we create a Service File to write reusable business logic and use it in controllers, forms, plugins, and other classes. Instead of writing the same code multiple times, we create a service once and inject it wherever required.

Let's understand with a practical example for your Drupal developer interview.

1. Create a custom Drupal service

Suppose your custom module name is custom_demo.

Create this folder structure:

modules/custom/custom_demo/

custom_demo.info.yml

custom_demo.services.yml

src/

MyCustomService.php

2. Define the service in custom_demo.services.yml

This file tells Drupal which PHP class should be registered as a service.

 

services:

  custom_demo.my_service:

    class: Drupal\custom_demo\MyCustomService

Explanation:

  • custom_demo.my_service — the unique service ID.
  • class — the PHP class Drupal will instantiate.

3. Create src/MyCustomService.php

<?php

namespace Drupal\custom_demo;

class MyCustomService {

               public function getMessage() {

                              return 'Hello from Drupal Service!';

               }

}

This class contains the reusable business logic.

4. Use the service in a Controller

Create src/Controller/DemoController.php.

<?php

namespace Drupal\custom_demo\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\DependencyInjection\ContainerInterface;

use Drupal\custom_demo\MyCustomService;

class DemoController extends ControllerBase {

  protected $myService;

  public function __construct(MyCustomService $my_service) {

                $this->myService = $my_service;

  }

  public static function create(ContainerInterface $container) {

    return new static(

      $container->get('custom_demo.my_service')

    );

  }

  public function showMessage() {

    return [

      '#markup' => $this->myService->getMessage(),

    ];

  }

}

5. Add a route

Create custom_demo.routing.yml:

custom_demo.demo:

  path: '/custom-demo'

  defaults:

    _controller: '\Drupal\custom_demo\Controller\DemoController::showMessage'

    _title: 'Custom Service Demo'

  requirements:

    _permission: 'access content'

 

6. Clear Drupal cache

Run this command from your Drupal project root:

drush cr

Now open:

https://your-site.com/custom-demo

Expected output:

Hello from Drupal Service!

7. How dependency injection works

The important part is:

$container->get('custom_demo.my_service')

Drupal's service container retrieves the registered service and passes it to the controller constructor. This technique is called Dependency Injection (DI).

 

Interview question: How do you create a service in Drupal?

A good answer for your experience level:

“In Drupal 8 and later versions, I create a service by defining it in the module's .services.yml file and implementing its logic in a PHP class under the src directory.

 I register the class using a service ID and inject the service into a controller or another class through dependency injection.

This helps me reuse business logic, improve maintainability, and make the code easier to test.”

Copy answer

Remember: A service is not the same as a controller. A service contains reusable logic; a controller handles the request and returns a response.

 

Q8. What is Layout Builder in Drupal?

Answer:

Layout Builder is a Drupal feature that allows administrators and content editors to create page layouts using sections and blocks through a visual interface.

I use it to create flexible page layouts, place reusable blocks, and configure layouts for content types or individual content items. It reduces the need to create separate templates for every page layout.

 

Q10. What is configuration management in Drupal?

Answer:

Configuration Management allows us to export and import site configuration using YAML files.

It includes content types, fields, views, roles, and other configuration.

I use drush cex to export configuration and drush cim to import it. Before importing into another environment, I review the changes and ensure that configuration dependencies are available.

 

4. Multisite architecture

Q11. What is Drupal multisite architecture?

Answer:

Drupal multisite allows multiple websites to run from a shared Drupal codebase. Each site can have its own database, files directory, settings, and site-specific configuration.

It helps reduce code duplication and simplifies maintenance when multiple websites share similar functionality. However, shared code updates must be tested carefully because they can affect all sites using that codebase.

Q12. How do you configure Drupal multisite?

Answer:

I configure the shared Drupal codebase and create separate site directories under sites, such as sites/site1.com and sites/site2.com. Each site has its own settings file and database configuration.

I also configure the web server's domain mapping, permissions, files directories, and environment-specific settings. Finally, I test each site's routing, database connection, and configuration independently.

 

5. Acquia Cloud Platform

Q13. What is Acquia Cloud?

Answer:

Acquia Cloud is a managed platform for hosting and managing Drupal applications. It supports development workflows, deployment, environments, logs, and monitoring.

In a typical workflow, developers work in a development environment, test changes in staging, and promote approved code to production. I also use Git and Drush for code and configuration management where supported by the project's deployment process.

If your hands-on Acquia experience is limited, say that you understand the workflow and are ready to work with the platform rather than claiming direct production experience.

Q14. How do you troubleshoot an issue on Acquia Cloud?

Answer:

First, I reproduce the issue and check application logs, PHP errors, and Drupal watchdog logs. I verify recent deployments, configuration changes, database connectivity, and cache behavior.

If necessary, I use Drush to inspect the site, clear caches, and validate configuration. I test the fix in a non-production environment before deploying it to production.

 

6. REST API integrations

Q15. How do you integrate a third-party REST API in Drupal?

Answer:

I use Drupal's HTTP client service, which is based on Guzzle, to send requests to external APIs. I handle authentication, request parameters, response codes, JSON decoding, exceptions, and timeouts.

I keep API credentials in environment-specific configuration rather than hardcoding secrets. I also implement appropriate error handling, logging, and caching when the response can be safely cached.

Example: For Service

$endpoint = 'https://api.example.com/data';

$response = $this->httpClient->request ('GET',  $endpoint,

[ 'headers' => [

 'Accept' => 'application/json',

'Authorization' => 'Bearer YOUR_API_TOKEN',

],

'timeout' => 10,

]

);

$body = $response->getBody()->getContents();

This code belongs inside a class where the HTTP client has been injected as a dependency.

. Module
$client = \Drupal::httpClient()

$response = $client->get('https://example.com',

[

'query' => ['status' => 'active'], '

auth' => ['username', 'password'],

]);

 $data = Json_decode($response->getBody()->getContents());

Q. What is Drupal Security?

Interview Answer (Simple English):

Drupal security means protecting a Drupal website, its data, users, and functionality from unauthorized access, attacks, and vulnerabilities.

Drupal provides several built-in security features, such as user permissions, roles, input validation, output escaping, CSRF protection, and secure password handling.

How do you prevent SQL Injection?

Wrong approach:

$query = "SELECT * FROM users WHERE name = '$username'";

Directly inserting user input into SQL can cause SQL injection.

Correct Drupal approach:

$query = \Drupal::database()->select('users_field_data', 'u');
$query->fields('u', ['name']);
$query->condition('u.name', $username);

$result = $query->execute()->fetchField();


Q17. What is the difference between REST and JSON:API?

Answer:

REST is an architectural style for designing web APIs. JSON:API is a standardized specification for exchanging JSON data and includes conventions for resources, relationships, filtering, and pagination.

Drupal provides JSON:API support for entity-based content, while Drupal REST can be configured for supported resource operations and formats. I choose the approach based on the project's integration requirements.

 

7. WCAG accessibility and SEO

Q18. What is WCAG, and how do you make a Drupal website accessible?

Answer:

WCAG stands for Web Content Accessibility Guidelines. These guidelines help make websites accessible to people with disabilities.

I use semantic HTML, meaningful headings, proper form labels, keyboard navigation, visible focus states, appropriate alternative text for images, and sufficient color contrast. I also check that interactive components work with assistive technologies and test pages using accessibility tools.

 

Q19. How do you improve SEO in Drupal?

Answer:

I use clean URLs, meaningful page titles, meta descriptions, appropriate heading structure, image alt text, XML sitemaps, and canonical URLs where needed.

I also check redirects, broken links, duplicate content, page performance, mobile responsiveness, and structured data where relevant. Modules such as Metatag, Pathauto, and Simple XML Sitemap can help implement these requirements.

 

8. Jira, Confluence, Figma, and UX

Q20. How do you use Jira and Confluence?

Answer:

I use Jira to track tasks, bugs, user stories, sprint work, and acceptance criteria. I update task status and communicate blockers to the team.

Confluence is useful for technical documentation, implementation notes, API specifications, and project knowledge sharing. Together, these tools help maintain transparency and collaboration.

Q21. How do you convert a Figma design into a Drupal website?

Answer:

First, I review the Figma design to understand the layout, typography, colors, spacing, responsive behavior, and reusable components. Then I map the design to Drupal content types, fields, blocks, Layout Builder, and Twig templates.

I implement responsive HTML and CSS, ensure accessibility, and compare the developed pages against the design. I also validate the layout on mobile, tablet, and desktop screens.

9. Performance and real project scenarios

Q22. How do you improve Drupal website performance?

Answer:

I start by identifying the bottleneck using logs, profiling, and performance measurements. Then I review Drupal page cache, dynamic page cache, render cache, cache tags, cache contexts, and cache max-age.

I optimize database queries, add appropriate indexes where needed, reduce unnecessary API calls, optimize images and assets, and use CDN or infrastructure-level caching when available. Finally, I compare performance before and after the changes.

Q23. How do you migrate content from Drupal 7 to Drupal 10 or 11?

Answer:

I first audit the source site's content types, fields, users, taxonomies, files, and custom functionality. Then I map the source fields to the destination structure and configure Drupal's Migrate API with the necessary source, process, and destination plugins.

I run migration tests, validate content counts and file references, review migration logs, and correct mapping issues. Before the final migration, I plan a content freeze or synchronization strategy to avoid losing changes.

 

Q24. How do you handle a production issue?

Answer:

First, I assess the impact and reproduce the issue if possible. I check application logs, recent code deployments, configuration changes, database queries, and cache behavior.

I identify the root cause, implement the smallest safe fix, and test it in a suitable environment. After deployment, I verify the result, monitor the application, and document the root cause and preventive actions.

 

Q25. How do you ensure code quality in a Drupal project?

Answer:

I follow Drupal coding standards and use services and dependency injection to keep the code maintainable. I validate permissions, sanitize output, use parameterized database queries, and avoid hardcoding environment-specific values.

I also review code through Git pull requests, use automated tests where appropriate, check configuration changes, and test the functionality before release.

 

10. Quick revision before the interview

Topic

Key points to remember

Custom modules

.info.yml, routing, services, controllers, plugins

Services

Service container, dependency injection

Content types

Fields, entity references, Views

Layout Builder

Sections, blocks, flexible layouts

Workflows

Draft, review, published, permissions

Multisite

Shared codebase, separate site settings and databases

Acquia Cloud

Environments, logs, deployment, Drush

REST APIs

Guzzle, JSON, authentication, errors

WCAG

Keyboard access, labels, alt text, contrast

SEO

Metatag, Pathauto, sitemap, canonical URLs

Jira/Confluence

Tasks, bugs, documentation

Figma

Responsive implementation, design consistency

 

Q. What is Drupal? 

A: Drupal is an open-source Content Management System (CMS) built with PHP and Symfony components, used to create scalable and secure websites.

Q. What is a Custom Module? 

A: A custom module contains business-specific functionality that is not available in Drupal core or contributed modules. 

Q. Difference between Custom Module and Contributed Module? 

A: Custom modules are developed for project-specific requirements, while contributed modules are community-developed modules available on Drupal.org. 

Q. What is Twig? 

A: Twig is Drupal's templating engine used for rendering HTML while separating presentation from business logic. 

Q. What is Layout Builder? 

A: Layout Builder is a core Drupal module in Drupal 8.6+ that allows content editors to create and customize page layouts through a drag-and-drop interface. 

Scenario:- Layout Builder is a Drupal feature that allows administrators and content editors to create page layouts using sections and blocks through a visual interface.

I use it to create flexible page layouts, place reusable blocks, and configure layouts for content types or individual content items. It reduces the need to create separate templates for every page layout.

Q. How do you optimize frontend performance? 

A: I optimize images, use lazy loading, minify CSS/JS, enable caching, reduce API calls, and optimize DOM rendering. 

Q. What is Lazy Loading? 

A: Lazy loading loads resources only when needed, improving page speed and reducing initial load time. 

Q. How do you improve SEO in Drupal?

A: I use clean URLs, meaningful page titles, meta descriptions, appropriate heading structure, image alt text, XML sitemaps, and canonical URLs where needed.

I also check redirects, broken links, duplicate content, page performance, mobile responsiveness, and structured data where relevant. Modules such as Metatag, Pathauto, and Simple XML Sitemap can help implement these requirements.

Q. What are Hooks? 

A: Hooks allow modules to “react” to events triggered by Drupal. 

Definition: - "Hooks are an important extension mechanism in Drupal. They allow us to modify or extend existing Drupal functionality without changing Drupal core code.

For example, if a client wants to send a welcome email whenever a new user registers, we can implement hook_user_insert() or another suitable user registration hook.

I have used hooks for form alterations, entity operations, custom business logic and modifying Drupal functionality."

Q. What is Caching in Drupal? 

 

A: Caching in Drupal is a mechanism used to improve website performance by storing frequently accessed data and previously rendered output.

Drupal provides different caching mechanisms, such as: -

Internal Page Cache, Dynamic Page Cache, Render Cache, Entity Cache, and Views Cache.

In Drupal 8 onwards, we mainly work with three important cache properties:

Cache Tags: - help invalidate cached data when content changes.

Cache Contexts: - help create different cache variations based on users, roles, languages, or URL parameters.

Cache Max-Age: - defines how long the cached data remains valid.

In my projects, I use these caching mechanisms to improve performance and ensure users receive updated information when content changes.

Types of caching in Drupal

Drupal 8, 9, 10 and 11 have several important caching mechanisms.

1. Internal Page Cache

  • Mainly caches complete pages for anonymous users and Useful for websites with many visitors.
  • Reduces repeated page generation.

2. Dynamic Page Cache

  • Caches page content for both anonymous and authenticated users.

3. Render Cache

  • Stores rendered output of individual render elements, blocks, and components and avoids repeatedly rendering the same components.

4. Entity Cache

  • Stores loaded entity objects during a request and avoid loading the same entity repeatedly.

5. Views Cache

  • Stores Views query results or rendered output, depending on the configured caching plugin.
  • Reduces repeated processing of listings.

6. Database Cache Backend

  • Drupal can store cache items in database tables and other cache backends, such as Redis, can also be configured.

Q.  Custom Module Explanation

A:  A custom module in Drupal is created to add new features or override existing functionality that cannot be handled by contrib modules. A custom module usually includes: 

  • module_name.info.yml — module metadata  
  • module_name.routing.yml — defines routes  
  • module_name.controllers — logic for pages  
  • module_name.services.yml — register services  
  • module_name.module — hooks implementation 

Steps to create a custom module:  

  1. Create a folder under /modules/custom.  
  1. Add .info.yml file.  
  1. Add routing, controller, and services as needed.  
  1. Clear cache & enable the module.  
  1. Implement hooks or business logic." 

Example: Creating custom form, REST API, cron, block, service, etc. 

Definition: - In Drupal, we create custom modules to implement project-specific business requirements that cannot be handled by existing core or contributed modules.

First, we create a folder inside the modules/custom directory and add an info.yml file to define the module information.

Then, depending on the requirements, we create routing files, controllers, forms, services, plugins, and event subscribers.

We also use hooks to alter or extend existing Drupal functionality.

Finally, we enable the module using Drush and rebuild the cache.

Migration API Explanation

A:  Drupal's Migrate API is used to migrate content, files, taxonomy, and users from older Drupal versions or external sources. 
A migration consists of:  

  • Source: CSV, JSON, SQL, XML, Drupal 7 database  (Data kahan se aa raha hai.)
  • Process: Mapping fields using process plugins  (Data ko kaise transform aur map karna hai.)
  • Destination: Drupal entities (node, taxonomy, files) (Data Drupal mein kahan save hoga.)

Common plugins:  

  • get, concat, explode, migration_lookup, entity_lookup 

Command: 
drush migrate-import migration_id 
drush migrate-rollback migration_id

Definition: - Drupal Migrate API is used to migrate data from Drupal 7, external databases, CSV, JSON, and XML sources into Drupal.

It mainly consists of three stages: Source, Process, and Destination.

Source is where we fetch the data. Process is used to transform and map the fields using process plugins. Destination defines where we want to save the data, such as nodes, users, taxonomy terms, or files.

I have used migration plugins like get, concat, migration_lookup, and entity_lookup for data mapping and transformation.

We can execute migrations using Drush commands and validate the migrated data after completion.

 

Q. What is Dependency Injection in Drupal, and why do we use it instead of creating objects directly? 

 

A:  "Dependency Injection is a design pattern in which a class receives the services or objects it needs from outside instead of creating them directly.

In Drupal, we use Dependency Injection to access services like the database, current user, entity manager, and logger.

We inject these services through the constructor using Drupal's Service Container.

For example, if I want to get the current logged-in user's information in a custom controller, I inject the current_user service through the constructor.

The main benefits are loose coupling, code reusability, better maintainability, and easier unit testing.

In Drupal, Dependency Injection is preferred over directly using the global \Drupal static service calls inside class-based code."

 

Dependency Injection in Drupal – Practical example

Suppose we want to get the current logged-in user's information.

Without Dependency Injection (Not recommended in class-based code):

$current_user = \Drupal::currentUser();

$user_id = $current_user->id();

Here we are directly accessing the global Drupal service container using the static service locator.

With Dependency Injection (Recommended):

 

Step 1: Create a custom service class.

File: src/Service/EmployeeService.php

<?php

namespace Drupal\employee_management\Service;

use Drupal\Core\Session\AccountProxyInterface;

class EmployeeService {

  protected $currentUser;

  public function __construct(AccountProxyInterface $current_user) {

    $this->currentUser = $current_user;

  }

  public function getCurrentUserId() {

    return $this->currentUser->id();

  }

}

 

Step 2: Register the service.

File: employee_management.services.yml

services:

  employee_management.employee_service:

                class: Drupal\employee_management\Service\EmployeeService

                arguments: ['@current_user']

 

Step 3: Use the service.

$employee_service = \Drupal::service('employee_management.employee_service');

$user_id = $employee_service->getCurrentUserId();

Here, @current_user tells Drupal's service container to inject the current user service into the constructor.

 

5. How to inject a service into a Controller?

A: This is a very common practical interview question.

Example: Inject the current user service into a custom controller.

<?php

namespace Drupal\employee_management\Controller;

use Drupal\Core\Controller\ControllerBase;

use Drupal\Core\Session\AccountProxyInterface;

use Symfony\Component\DependencyInjection\ContainerInterface;

class EmployeeController extends ControllerBase {

  protected $currentUser;

  public function __construct(AccountProxyInterface $current_user) {

    $this->currentUser = $current_user;

  }

 

  public static function create(ContainerInterface $container) {

    return new static(

      $container->get('current_user')

    );

  }

  public function employeeList() {

    $user_id = $this->currentUser->id();

    return [

      '#markup' => 'Current User ID: ' . $user_id,

    ];

  }

}

Understand these three things:

  1. __construct() – Receives the dependency.
  2. create() – Gets the service from Drupal's container and passes it to the constructor.
  3. $this->currentUser – Allows us to use the injected service inside the class.

6. Benefits of Dependency Injection

  1. Loose coupling: Classes are less dependent on specific implementations.
  2. Reusability: Services can be reused in multiple classes.
  3. Testability: We can mock services during unit testing.
  4. Maintainability: Code becomes easier to manage.
  5. Flexibility: Dependencies can be replaced without changing the main business logic.

 





 

No comments:

Post a Comment

If you have any problem please let me know.