PHP TypeLang Help

Data Mapper

A mapper is a system that transforms internal data into external data (normalization) and vice versa (denormalization) using a set of declarative transformation rules.

A mapper can be used in the ACL layer (anti-corruption) for transforming DTOs or for interacting with the database (converting primitive data into full-fledged entities and value objects). It can also be used for serialization and deserialization of data in command or query buses. It can also be used to transform JSON data in APIs into full-fledged DTOs, and much more.

Installation

Requirements:

  • PHP >= 8.1

  • ext-pcre

Usage

To create a mapper, you should use instantiation of the TypeLang\Mapper\Mapper object, after which the code is ready to use.

$mapper = new TypeLang\Mapper\Mapper();

The mapper contains two transformation directions:

  • Normalization - the process of converting complex internal application data to external data (API, database, etc.)

    $mapper = new TypeLang\Mapper\Mapper(); $result = $mapper->normalize(new Example());
  • Denormalization - the process of converting simple external data to internal application data types

    $mapper = new TypeLang\Mapper\Mapper(); $result = $mapper->denormalize($data, Example::class);

As you can see, the denormalization process requires information about the type to which the incoming data will be converted.

With normalization, the type is optional, as it can be determined automatically based on the incoming data, but can also be explicitly specified as a second argument.

$mapper->normalize(new Example(), Example::class);

The type specified in the second argument of the normalization and denormalization methods can be arbitrary, as described in the language grammar section.

An example of this "type definition" is shown below. However, the capabilities (and existence) of this type depend on the platform.

$result = $mapper->normalize(new Example(), <<<'PHP' object{ field: non-empty-string, another: int<0, max>, } PHP);

The types themselves, their availability, capabilities, functionality and behavior depend on the selected platform.

Customization

The Mapper can also take several additional arguments.

$mapper = new TypeLang\Mapper\Mapper( [[[platform: ...,|mapper-platforms.html]]] [[[config: ...,|mapper-configuration.html]]] [[[typeExtractorFactory: ...,|type-extractors.html]]] typeParserFactory: ..., typeRepositoryFactory: ..., );
  • platform - Allows to specify a set of specific types, type coercers, and syntax rules

  • config - Allows to specify a custom configuration

  • typeExtractorFactory - Allows to specify custom rules for inferring types from values

  • typeParserFactory - Allows to specify custom type parsing rules

  • typeRepositoryFactory - Allows to specify a custom implementation of the type registry (repository)

05 November 2025