Fundamentals
Types
In PHP AutoMapper, the types of class properties play a crucial role in how mapping is performed. The types are determined using the Symfony PropertyInfo component. This means you can use PHP type hints or PHPDoc type hints to define the types of your properties.
Here's an example:
class SourceClass {
/**
* @var string[]
*/
private array $titles;
}
In the above example, the titles member is a typed array of strings.
Default Mapping
By default, AutoMapper will automatically map the values if the source and destination types match.
For instance, if a member in the source class is of type string
and the corresponding member
in the destination class is also of type string
, AutoMapper will automatically map the value without
further configuration.
Customizing Type Conversion
In cases where the source and destination types do not match (e.g., mapping a string
to an int
),
a custom mapping is required. This can be achieved using the forMember
method and providing a custom
mapping function.
Here's an example:
class SourceClass {
public string $age;
}
class DestinationClass {
public int $age;
}
$config = new MapperConfiguration(fn (Config $config) => $config
->createMap(SourceClass::class, DestinationClass::class)
->createMap('string', 'int')
->convertUsing(fn (string $source, ResolutionContextInterface $context): int => intval($source))
);
In this example, we're mapping the age
member of SourceClass
(which is a string
) to the age
member of DestinationClass
(which is an int
). The custom mapping function converts the string to an
integer before mapping.