WordPress plugin: native DTOs
For plugin code that moves structured data between request input, options,
meta, custom tables, external APIs, REST controllers, admin screens, cron jobs,
and presenters. A DTO gives that data one named shape instead of leaking raw
arrays across the plugin.
This skill is intentionally better-data-free. If the project already uses
better-data, run bd-data-object; otherwise use this native pattern.
When to load references
- Need a complete PHP 7.4 / PHP 8.1 DTO implementation, nested DTO, enum-like value set, or secret value object: read references/native-dto-patterns.md.
- Refactoring a controller/repository that currently passes raw arrays,
$_POST, WP_Post, meta arrays, or option arrays around: read references/before-after-raw-array.md.
Misconception this skill corrects
"A DTO is just an array with nicer comments."
Wrong direction. A DTO is a small immutable boundary object with a named schema,
explicit defaults, and one hydration path. It prevents common AI mistakes:
unchecked (int) casts, empty() swallowing 0, isset() hiding intentional
null, dynamic properties, leaking secrets through to_array(), and passing
$_POST or raw post meta directly to business logic.
When to use this skill
Trigger when ANY of the following is true:
- Introducing
FooDto, FooData, SettingsData, RequestData, Payload, or a value object.
- A repository, REST controller, admin page, cron job, or WooCommerce hook currently passes large associative arrays around.
- Data comes from
$_GET, $_POST, REST params, options, post meta, user meta, term meta, custom tables, WP_Post, WP_User, or WooCommerce objects.
- Reviewing hydration / normalization code with casts like
(int), (bool), intval, settype, empty, isset, get_object_vars, or dynamic property assignment.
- Presenter or REST response code needs a stable input object.
Layer boundaries
| Layer |
Responsibility |
| Source / repository |
Read WP objects, options, meta, request params, API responses. Knows WordPress. |
| DTO |
Hold normalized values. No DB writes, no HTML, no hooks, no global reads. |
| Validator |
Decide whether the DTO is acceptable. Returns true or WP_Error. |
| Presenter |
Convert DTO to arrays / JSON-ready values for REST, admin, JS config, email. |
| View / template |
Escape and echo HTML. |
The DTO may contain small normalization helpers, but it should not call
get_post_meta(), update_option(), wp_remote_get(), add_action(), or echo
anything.
Minimal class shape
Prefer PHP 7.4-compatible immutable objects unless the plugin has a higher
minimum PHP version. Use PHP 8.1 readonly only when the plugin declares PHP
8.1+.
namespace MyPlugin\Dto;
use WP_Error;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
final class ProductDto {
private int $id;
private string $title;
public function __construct( int $id = 0, string $title = '' ) {
$this->id = $id;
$this->title = $title;
}
/** @param array<string,mixed> $data @return self|WP_Error */
public static function from_array( array $data ) {
$errors = new WP_Error();
$id = self::to_int( $data['id'] ?? 0, 'id', $errors );
$title = self::to_string( $data['title'] ?? '', 'title', $errors );
if ( '' === $title ) {
$errors->add( 'missing_title', 'Product title is required.' );
}
if ( $errors->has_errors() ) {
return $errors;
}
return new self( $id, $title );
}
/** @return array<string,mixed> */
public function to_array(): array {
return array(
'id' => $this->id,
'title' => $this->title,
);
}
public function id(): int { return $this->id; }
public function title(): string { return $this->title; }
private static function to_int( $value, string $field, WP_Error $errors ): int {
if ( is_int( $value ) ) {
return $value;
}
if ( is_string( $value ) && preg_match( '/^-?\d+$/', $value ) ) {
return (int) $value;
}
$errors->add( 'invalid_' . $field, sprintf( '%s must be an integer.', $field ) );
return 0;
}
private static function to_string( $value, string $field, WP_Error $errors ): string {
if ( is_string( $value ) ) {
return $value;
}
if ( is_scalar( $value ) ) {
return (string) $value;
}
$errors->add( 'invalid_' . $field, sprintf( '%s must be a string.', $field ) );
return '';
}
}
Use references/native-dto-patterns.md for
the full pattern: floats, booleans, DateTime, nested DTO collections, secrets,
with(), and PHP 8.1 variants.
Hydration rules
- One entry point. Use
from_array() or named factories like from_post( WP_Post $post ), from_option( array $option ), from_request( WP_REST_Request $request ).
- Sanitize at the input boundary, validate in/near the DTO. For
$_POST, use wp_unslash() first, then a field-specific sanitizer.
- Use allowlists. Read only known keys. Do not keep unknown keys unless the DTO has a deliberate
extra property.
- Use
array_key_exists() when null is meaningful. isset( $data['expires_at'] ) treats explicit null as absent.
- Avoid
empty() for typed fields. empty( '0' ) and empty( 0 ) are true.
- Coerce deliberately.
(int) 'abc' becomes 0; (bool) 'false' becomes true. Reject surprising input with WP_Error.
- Nested arrays become nested DTOs. Do not leave
items as random arrays when the plugin expects item shape.
- No dynamic properties. PHP 8.2 deprecates them. Declare every property.
- Defaults are explicit. Every constructor argument has a sensible default or is nullable.
Sensitive fields
DTOs often carry API keys, tokens, customer emails, or internal notes.
- Keep secrets nullable: absence is
null, not an empty secret string.
- Do not include secrets in
to_array() unless the method name says so, e.g. to_private_array().
- Prefer a tiny value object for credentials; see references/native-dto-patterns.md.
- Let the presenter decide whether a field is redacted for REST/admin/export.
Critical rules
- DTO is immutable. No setters. Use
with() to produce a changed copy.
- DTO is not a repository. No
get_post_meta(), no update_option(), no $wpdb, no HTTP calls.
- DTO is not a presenter. No HTML, no escaping, no
wp_send_json(), no rest_ensure_response().
- Hydration is explicit and allowlisted. Never
foreach ( $data as $key => $value ) { $dto->$key = $value; }.
- Validation returns
WP_Error or throws only for programmer errors. User input failures are normal and reportable.
- Use field-specific coercion. Do not use unchecked
(int), (bool), intval, settype, or empty()-driven normalization.
- Keep parameter/property names stable. Renaming
created_at to createdAt is a breaking change unless every caller and presenter is updated.
- For PHP 8.1 enums, use
tryFrom() and handle null. For PHP 7.4-compatible plugins, use constants plus explicit in_array( ..., true ).
Common mistakes
// WRONG - unchecked casts hide bad input.
$dto = new ProductDto( (int) $_POST['id'], (float) $_POST['price'] );
// WRONG - dynamic property hydration.
foreach ( $row as $key => $value ) {
$dto->{$key} = $value;
}
// WRONG - empty() rejects valid values.
if ( empty( $data['quantity'] ) ) {
return new WP_Error( 'missing_quantity', 'Quantity is required.' );
}
// WRONG - leaking secrets by dumping all object properties.
return get_object_vars( $dto );
Cross-references
- Run
wp-plugin-presenter when converting this DTO into REST/admin/JS/email output.
- Run
wp-plugin-architecture when deciding folder placement, namespaces, or by-feature vs by-type organization.
- Run
wp-plugin-options-storage when the DTO represents an option payload.
- Run
bd-data-object only if the project intentionally uses the better-data library. better-data automates many of these rules; this skill is the native no-library version.
What this skill does NOT cover
- HTML templates and escaping strategy after presentation.
- Database schema migrations or custom table repositories.
- better-data attributes, sources, sinks, or presenter builder APIs.
- REST route registration; use the REST-specific plugin skill if present.
References
- references/native-dto-patterns.md - complete DTO implementation patterns.
- references/before-after-raw-array.md - refactoring raw arrays into DTOs.
- WordPress input security:
wp_unslash(), sanitization, validation, and escaping.
WP_Error for user-input validation failures.
1---2name: wp-plugin-dto3description: Design and review native DTOs in WordPress plugins without4 requiring better-data - immutable data carriers, explicit from_array5 hydration, strict coercion instead of unchecked casts, WP_Error6 validation failures, sensitive-field discipline, nested DTO arrays, and7 clear separation from repositories, WP models, presenters, REST8 controllers, and HTML views. Use when a plugin introduces FooDto,9 request DTOs, settings DTOs, value objects, admin-row data shapes, REST10 response source objects, or when reviewing code that passes raw arrays,11 stdClass, WP_Post, WC_Order, $_POST, post meta, or option arrays through12 multiple layers. Mentions better-data only as an optional higher-level13 library; this skill is for native implementations.14author: Soczo Kristof15contact: mailto:lonsdale201@hotmail.com16plugin: wordpress17plugin-version-tested: "6.3 - 6.9"18php-min: "7.4"19last-updated: "2026-04-29"20docs:21 - https://developer.wordpress.org/plugins/security/securing-input/22 - https://developer.wordpress.org/plugins/security/validating-sanitizing-escaping/23 - https://developer.wordpress.org/reference/classes/wp_error/24 - https://developer.wordpress.org/reference/functions/wp_unslash/25metadata:26 source: https://skillmd.com/skills/vikingokft/wp-plugin-dto27---2829# WordPress plugin: native DTOs3031For plugin code that moves structured data between request input, options,32meta, custom tables, external APIs, REST controllers, admin screens, cron jobs,33and presenters. A DTO gives that data one named shape instead of leaking raw34arrays across the plugin.3536This skill is intentionally **better-data-free**. If the project already uses37better-data, run `bd-data-object`; otherwise use this native pattern.3839## When to load references4041- Need a complete PHP 7.4 / PHP 8.1 DTO implementation, nested DTO, enum-like value set, or secret value object: read [references/native-dto-patterns.md](references/native-dto-patterns.md).42- Refactoring a controller/repository that currently passes raw arrays, `$_POST`, `WP_Post`, meta arrays, or option arrays around: read [references/before-after-raw-array.md](references/before-after-raw-array.md).4344## Misconception this skill corrects4546> "A DTO is just an array with nicer comments."4748Wrong direction. A DTO is a small immutable boundary object with a named schema,49explicit defaults, and one hydration path. It prevents common AI mistakes:50unchecked `(int)` casts, `empty()` swallowing `0`, `isset()` hiding intentional51`null`, dynamic properties, leaking secrets through `to_array()`, and passing52`$_POST` or raw post meta directly to business logic.5354## When to use this skill5556Trigger when ANY of the following is true:5758- Introducing `FooDto`, `FooData`, `SettingsData`, `RequestData`, `Payload`, or a value object.59- A repository, REST controller, admin page, cron job, or WooCommerce hook currently passes large associative arrays around.60- Data comes from `$_GET`, `$_POST`, REST params, options, post meta, user meta, term meta, custom tables, `WP_Post`, `WP_User`, or WooCommerce objects.61- Reviewing hydration / normalization code with casts like `(int)`, `(bool)`, `intval`, `settype`, `empty`, `isset`, `get_object_vars`, or dynamic property assignment.62- Presenter or REST response code needs a stable input object.6364## Layer boundaries6566| Layer | Responsibility |67|---|---|68| Source / repository | Read WP objects, options, meta, request params, API responses. Knows WordPress. |69| DTO | Hold normalized values. No DB writes, no HTML, no hooks, no global reads. |70| Validator | Decide whether the DTO is acceptable. Returns `true` or `WP_Error`. |71| Presenter | Convert DTO to arrays / JSON-ready values for REST, admin, JS config, email. |72| View / template | Escape and echo HTML. |7374The DTO may contain small normalization helpers, but it should not call75`get_post_meta()`, `update_option()`, `wp_remote_get()`, `add_action()`, or echo76anything.7778## Minimal class shape7980Prefer PHP 7.4-compatible immutable objects unless the plugin has a higher81minimum PHP version. Use PHP 8.1 `readonly` only when the plugin declares PHP828.1+.8384```php85namespace MyPlugin\Dto;8687use WP_Error;8889if ( ! defined( 'ABSPATH' ) ) {90 exit;91}9293final class ProductDto {94 private int $id;95 private string $title;9697 public function __construct( int $id = 0, string $title = '' ) {98 $this->id = $id;99 $this->title = $title;100 }101102 /** @param array<string,mixed> $data @return self|WP_Error */103 public static function from_array( array $data ) {104 $errors = new WP_Error();105 $id = self::to_int( $data['id'] ?? 0, 'id', $errors );106 $title = self::to_string( $data['title'] ?? '', 'title', $errors );107108 if ( '' === $title ) {109 $errors->add( 'missing_title', 'Product title is required.' );110 }111 if ( $errors->has_errors() ) {112 return $errors;113 }114115 return new self( $id, $title );116 }117118 /** @return array<string,mixed> */119 public function to_array(): array {120 return array(121 'id' => $this->id,122 'title' => $this->title,123 );124 }125126 public function id(): int { return $this->id; }127 public function title(): string { return $this->title; }128129 private static function to_int( $value, string $field, WP_Error $errors ): int {130 if ( is_int( $value ) ) {131 return $value;132 }133 if ( is_string( $value ) && preg_match( '/^-?\d+$/', $value ) ) {134 return (int) $value;135 }136 $errors->add( 'invalid_' . $field, sprintf( '%s must be an integer.', $field ) );137 return 0;138 }139140 private static function to_string( $value, string $field, WP_Error $errors ): string {141 if ( is_string( $value ) ) {142 return $value;143 }144 if ( is_scalar( $value ) ) {145 return (string) $value;146 }147 $errors->add( 'invalid_' . $field, sprintf( '%s must be a string.', $field ) );148 return '';149 }150}151```152153Use [references/native-dto-patterns.md](references/native-dto-patterns.md) for154the full pattern: floats, booleans, DateTime, nested DTO collections, secrets,155`with()`, and PHP 8.1 variants.156157## Hydration rules158159- **One entry point.** Use `from_array()` or named factories like `from_post( WP_Post $post )`, `from_option( array $option )`, `from_request( WP_REST_Request $request )`.160- **Sanitize at the input boundary, validate in/near the DTO.** For `$_POST`, use `wp_unslash()` first, then a field-specific sanitizer.161- **Use allowlists.** Read only known keys. Do not keep unknown keys unless the DTO has a deliberate `extra` property.162- **Use `array_key_exists()` when `null` is meaningful.** `isset( $data['expires_at'] )` treats explicit `null` as absent.163- **Avoid `empty()` for typed fields.** `empty( '0' )` and `empty( 0 )` are true.164- **Coerce deliberately.** `(int) 'abc'` becomes `0`; `(bool) 'false'` becomes `true`. Reject surprising input with `WP_Error`.165- **Nested arrays become nested DTOs.** Do not leave `items` as random arrays when the plugin expects item shape.166- **No dynamic properties.** PHP 8.2 deprecates them. Declare every property.167- **Defaults are explicit.** Every constructor argument has a sensible default or is nullable.168169## Sensitive fields170171DTOs often carry API keys, tokens, customer emails, or internal notes.172173- Keep secrets nullable: absence is `null`, not an empty secret string.174- Do not include secrets in `to_array()` unless the method name says so, e.g. `to_private_array()`.175- Prefer a tiny value object for credentials; see [references/native-dto-patterns.md](references/native-dto-patterns.md#secret-value-object).176- Let the presenter decide whether a field is redacted for REST/admin/export.177178## Critical rules179180- **DTO is immutable.** No setters. Use `with()` to produce a changed copy.181- **DTO is not a repository.** No `get_post_meta()`, no `update_option()`, no `$wpdb`, no HTTP calls.182- **DTO is not a presenter.** No HTML, no escaping, no `wp_send_json()`, no `rest_ensure_response()`.183- **Hydration is explicit and allowlisted.** Never `foreach ( $data as $key => $value ) { $dto->$key = $value; }`.184- **Validation returns `WP_Error` or throws only for programmer errors.** User input failures are normal and reportable.185- **Use field-specific coercion.** Do not use unchecked `(int)`, `(bool)`, `intval`, `settype`, or `empty()`-driven normalization.186- **Keep parameter/property names stable.** Renaming `created_at` to `createdAt` is a breaking change unless every caller and presenter is updated.187- **For PHP 8.1 enums, use `tryFrom()` and handle null.** For PHP 7.4-compatible plugins, use constants plus explicit `in_array( ..., true )`.188189## Common mistakes190191```php192// WRONG - unchecked casts hide bad input.193$dto = new ProductDto( (int) $_POST['id'], (float) $_POST['price'] );194195// WRONG - dynamic property hydration.196foreach ( $row as $key => $value ) {197 $dto->{$key} = $value;198}199200// WRONG - empty() rejects valid values.201if ( empty( $data['quantity'] ) ) {202 return new WP_Error( 'missing_quantity', 'Quantity is required.' );203}204205// WRONG - leaking secrets by dumping all object properties.206return get_object_vars( $dto );207```208209## Cross-references210211- Run **`wp-plugin-presenter`** when converting this DTO into REST/admin/JS/email output.212- Run **`wp-plugin-architecture`** when deciding folder placement, namespaces, or by-feature vs by-type organization.213- Run **`wp-plugin-options-storage`** when the DTO represents an option payload.214- Run **`bd-data-object`** only if the project intentionally uses the better-data library. better-data automates many of these rules; this skill is the native no-library version.215216## What this skill does NOT cover217218- HTML templates and escaping strategy after presentation.219- Database schema migrations or custom table repositories.220- better-data attributes, sources, sinks, or presenter builder APIs.221- REST route registration; use the REST-specific plugin skill if present.222223## References224225- [references/native-dto-patterns.md](references/native-dto-patterns.md) - complete DTO implementation patterns.226- [references/before-after-raw-array.md](references/before-after-raw-array.md) - refactoring raw arrays into DTOs.227- WordPress input security: `wp_unslash()`, sanitization, validation, and escaping.228- `WP_Error` for user-input validation failures.