Use when creating or reviewing a DTO or value object in a custom Drupal module, or when replacing a structured associative array passed between services or returned by an external API, AI or MCP integration with a typed class. Not for entities, configuration, form state or render arrays.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Drupal Dto?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/siva01c-drupal-dto)
---
name: drupal-dto
description: Use when creating or reviewing a DTO or value object in a custom Drupal module, or when replacing a structured associative array passed between services or returned by an external API, AI or MCP integration with a typed class. Not for entities, configuration, form state or render arrays.
---
# Drupal DTO Skill
## Purpose
Give structured data an explicit, typed contract. DTOs buy readability, static analysis and safe refactoring. They are not a performance optimization: do not swap arrays for objects for speed without a benchmark.
## Decide first
Check for an existing DTO or an equivalent class before adding one.
Use a DTO when:
- a stable structure crosses a service or layer boundary,
- an external response (API, AI, RAG, MCP) needs normalizing,
- several parameters form one logical request.
Keep an array or the Drupal object when:
- the data is small, local or temporary,
- a Drupal API expects an array (render arrays, plugin definitions),
- Drupal already models it: entities, configuration, form state, cache metadata, Typed Data API.
When reviewing existing code, recommend a DTO only if you can name the concrete defect or friction it removes. Do not refactor unrelated code.
## Check the PHP baseline
Read `composer.json` (`require.php`, `config.platform.php`, core constraint) before writing code.
| Supported core | PHP floor | Form |
|---|---|---|
| Drupal 11+ only | 8.3 (Drupal 12: 8.5) | `final readonly class` |
| Also Drupal 10 | 8.1 | `final class` with `readonly` on each property |
The examples below target Drupal 11+. Do not add an external DTO library unless the project asks for one.
## Placement and design
- Default to `src/Dto/` (`Drupal\my_module\Dto`). If the module groups classes by domain (for example `src/Search/SearchResult.php`), follow that instead.
- Name the data (`SearchResult`, `EmbeddingResult`), never `Data` or `Container`.
- No services, container calls, queries or HTTP inside a DTO, and do not register it as a service.
- Invariants and mapping to or from its own shape belong in the DTO. Workflows and rules that need other services do not.
- `readonly` is shallow: an object held in a property can still change. Hold scalars, enums, `DateTimeImmutable` or other immutable DTOs.
- Nullable only when "no value" is a real state.
## Validate and normalize at the boundary
Untrusted input is checked once, where it enters. A request carries its own invariants, including an upper bound on anything that drives work:
```php
<?php
declare(strict_types=1);
namespace Drupal\my_module\Dto;
/**
* Represents a search request.
*/
final readonly class SearchRequest {
public const MAX_LIMIT = 100;
/**
* The search query without surrounding whitespace.
*/
public string $query;
/**
* Constructs a search request.
*
* @throws \InvalidArgumentException
* When the query is empty or the limit is out of range.
*/
public function __construct(
string $query,
public int $limit = 10,
) {
$this->query = trim($query);
if ($this->query === '') {
throw new \InvalidArgumentException('Search query cannot be empty.');
}
if ($limit < 1 || $limit > self::MAX_LIMIT) {
throw new \InvalidArgumentException('Search limit is out of range.');
}
}
}
```
External payloads get a named factory that checks presence and type of every key. Do not cast blindly (`(string) $data['title']` turns a missing value into `''`):
```php
<?php
declare(strict_types=1);
namespace Drupal\my_module\Dto;
/**
* Represents a search result.
*/
final readonly class SearchResult {
/**
* Constructs a search result.
*/
public function __construct(
public string $title,
public string $url,
public float $score,
public ?string $summary = NULL,
) {}
/**
* Creates a result from a decoded response item.
*
* @param array<mixed> $data
* The decoded item.
*
* @throws \UnexpectedValueException
* When a key is missing or has the wrong type.
*/
public static function fromArray(array $data): self {
$title = $data['title'] ?? NULL;
$url = $data['url'] ?? NULL;
$score = $data['score'] ?? NULL;
$summary = $data['summary'] ?? NULL;
if (!is_string($title) || !is_string($url)) {
throw new \UnexpectedValueException('Title and URL must be strings.');
}
// JSON decodes a whole number such as 1 as an integer.
if (!is_int($score) && !is_float($score)) {
throw new \UnexpectedValueException('Score must be a number.');
}
if ($summary !== NULL && !is_string($summary)) {
throw new \UnexpectedValueException('Summary must be a string.');
}
return new self($title, $url, (float) $score, $summary);
}
}
```
A type check does not make content safe. Check the URL scheme (`UrlHelper`) before linking to it and let Twig escape text. Entity and Form API validation stay where they are.
## Use from services
The service takes and returns DTOs; its dependencies are injected into the service, never into the DTO. The backend is the module's own interface, here next to the service:
```php
<?php
declare(strict_types=1);
namespace Drupal\my_module\Service;
/**
* Queries the search index.
*/
interface SearchBackendInterface {
/**
* Returns the decoded result rows, untrusted.
*
* @return array<mixed>
* The rows as the backend sent them.
*/
public function query(string $query, int $limit): array;
}
```
Decide what one bad item does to the whole response. For a result list, skip and log it, so one malformed row does not turn 19 good results into an error page. Where a partial result would be wrong (a payment, an import), let the exception through, declare it with `@throws` and handle it in the caller.
```php
<?php
declare(strict_types=1);
namespace Drupal\my_module\Service;
use Drupal\my_module\Dto\SearchRequest;
use Drupal\my_module\Dto\SearchResult;
use Psr\Log\LoggerInterface;
/**
* Provides search.
*/
final class SearchService {
/**
* Constructs the search service.
*/
public function __construct(
private readonly SearchBackendInterface $backend,
private readonly LoggerInterface $logger,
) {}
/**
* Searches for content, skipping malformed rows.
*
* @return \Drupal\my_module\Dto\SearchResult[]
* The search results.
*/
public function search(SearchRequest $request): array {
$results = [];
foreach ($this->backend->query($request->query, $request->limit) as $row) {
// A non-array row would raise a TypeError, not UnexpectedValueException.
if (!is_array($row)) {
$this->logger->warning('Skipped a search row that is not an array.');
continue;
}
try {
$results[] = SearchResult::fromArray($row);
}
catch (\UnexpectedValueException $e) {
$this->logger->warning('Skipped a malformed search row: @message', ['@message' => $e->getMessage()]);
}
}
return $results;
}
}
```
Add a collection class only when it has behavior of its own.
## Drupal boundaries
- **Render:** convert to a render array in the controller, block or formatter. Do not hand a DTO to the renderer.
- **Cacheability:** a DTO carries none. Keep tags, contexts and max-age from the source (`CacheableMetadata`) and apply them to the response or render array.
- **Entities:** convert only at a real boundary (public API, integration payload).
- **API output:** write the normalization explicitly. Public properties are not an API contract, and not every one should leave the site.
- **Stored DTOs:** a DTO put into a queue, cache, tempstore or state is serialized with its class shape. After a deploy that renames, adds or retypes a property, old records can unserialize into broken objects. Store a plain array with an explicit mapping, or drain/invalidate the storage in an update hook. `unserialize()` also skips the constructor, so its normalization and checks (`trim()`, the empty query, `MAX_LIMIT`) never run on a stored object: rebuild the DTO from the stored array through its constructor or factory when reading it back, and never unserialize one without `allowed_classes`.
## Tests
Unit tests, no kernel. Cover the mapping, the optional values and every rejected input, not only property assignment.
```php
<?php
declare(strict_types=1);
namespace Drupal\Tests\my_module\Unit\Dto;
use Drupal\my_module\Dto\SearchRequest;
use Drupal\my_module\Dto\SearchResult;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
/**
* Tests the search DTOs.
*/
#[Group('my_module')]
final class SearchDtoTest extends UnitTestCase {
/**
* Tests that an integer score and a missing summary are accepted.
*/
public function testFromArray(): void {
$result = SearchResult::fromArray([
'title' => 'Drupal',
'url' => '/drupal',
'score' => 1,
]);
self::assertSame(1.0, $result->score);
self::assertNull($result->summary);
}
/**
* Tests that malformed payloads are rejected.
*
* @param array<mixed> $data
* The payload.
*/
#[DataProvider('invalidPayloads')]
public function testFromArrayRejects(array $data): void {
$this->expectException(\UnexpectedValueException::class);
SearchResult::fromArray($data);
}
/**
* Provides malformed payloads.
*
* @return array<string, array{array<mixed>}>
* The cases.
*/
public static function invalidPayloads(): array {
$valid = ['title' => 'Drupal', 'url' => '/drupal', 'score' => 0.5];
return [
'empty' => [[]],
'title missing' => [array_diff_key($valid, ['title' => TRUE])],
'title not a string' => [['title' => 1] + $valid],
'url missing' => [array_diff_key($valid, ['url' => TRUE])],
'url not a string' => [['url' => ['/drupal']] + $valid],
'score missing' => [array_diff_key($valid, ['score' => TRUE])],
'score as string' => [['score' => '0.5'] + $valid],
'summary not a string' => [['summary' => []] + $valid],
];
}
/**
* Tests request normalization and the accepted limit bounds.
*/
public function testRequest(): void {
self::assertSame('drupal', (new SearchRequest(' drupal '))->query);
self::assertSame(1, (new SearchRequest('drupal', 1))->limit);
self::assertSame(SearchRequest::MAX_LIMIT, (new SearchRequest('drupal', SearchRequest::MAX_LIMIT))->limit);
}
/**
* Tests that invalid requests are rejected.
*
* @param string $query
* The query.
* @param int $limit
* The limit.
*/
#[DataProvider('invalidRequests')]
public function testRequestRejects(string $query, int $limit): void {
$this->expectException(\InvalidArgumentException::class);
new SearchRequest($query, $limit);
}
/**
* Provides invalid requests.
*
* @return array<string, array{string, int}>
* The cases.
*/
public static function invalidRequests(): array {
return [
'empty query' => ['', 10],
'whitespace query' => [' ', 10],
'limit zero' => ['drupal', 0],
'limit negative' => ['drupal', -1],
'limit over maximum' => ['drupal', SearchRequest::MAX_LIMIT + 1],
];
}
}
```
Drupal 10 runs PHPUnit 9, which reads only annotations: use `@group` and `@dataProvider` there. For code that runs on both, keep annotations and attributes together.
## Verify
Run in the project's container, with the project's own configuration (`phpcs.xml`, `phpstan.neon`, `phpunit.xml`) where it has one. With DDEV, prefix each command with `ddev exec`; with Docker Compose, with `docker compose exec <php-service>`. Take the docroot from `composer.json` (`extra.drupal-scaffold.locations.web-root`): `web/` below, often `docroot/` elsewhere.
```bash
ddev exec vendor/bin/phpcs --standard=Drupal,DrupalPractice path/to/my_module
ddev exec vendor/bin/phpstan analyse path/to/my_module
ddev exec vendor/bin/phpunit -c web/core path/to/my_module/tests/src/Unit
```