You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class User
{
publicstring$email;
}
class Order
{
publicstring$reference;
publicUser$customer;
}
class OrderDTO
{
publicstring$reference;
publicstring$customerEmail;
}
$customer = newUser();
$customer->email = '[email protected]';
$source = newOrder();
$source->reference = 'FAC9123';
$source->customer = $customer;
dump($autoMapper->map($source, OrderDTO::class));
// Will output://// OrderDTO {#14 🔽// +reference: "FAC9123"// +customerEmail: null// }
Map from Order to OrderDTO
To map data inside customerEmail, so far the only solution is to use a transformer:
class OrderDTO
{
publicstring$reference;
#[MapFrom(Order::class, transformer: "source.user.email")]
publicstring$customerEmail;
}
It's working but it's not very natural, a better DX would be:
class OrderDTO
{
publicstring$reference;
#[MapFrom(Order::class, property: "user.email")]
publicstring$customerEmail;
}
Map from OrderDTO to Order
The only way I found is to create a transformer and return a User object. Which is very problematic because sometimes, the User could have other values I don't want to lose.
class Order
{
publicstring$reference;
#[MapFrom(OrderDTO::class, transformer: [self, "mapUser"])
public User $customer;
publicstaticfunctionmapUser($val, $source) {
$user = newUser();
$user->email = $source->customerEmail;
return$user;
}
}
A better DX would have been:
class OrderDTO
{
public string $reference;
#[MapFrom(Order::class, property: "user.email")]
#[MapTo(Order::class, property: "user.email")]
public string $customerEmail;
}
And if "User" is null, throw an exception.
(End-user can use the "if" attribute option to prevent unwanted exceptions).
The text was updated successfully, but these errors were encountered:
I wish we could map nested objects back and forth with AutoMapper.
Let's take the example from #14:
Map from Order to OrderDTO
To map data inside customerEmail, so far the only solution is to use a transformer:
It's working but it's not very natural, a better DX would be:
Map from OrderDTO to Order
The only way I found is to create a transformer and return a User object. Which is very problematic because sometimes, the User could have other values I don't want to lose.
A better DX would have been:
And if "User" is null, throw an exception.
(End-user can use the "if" attribute option to prevent unwanted exceptions).
The text was updated successfully, but these errors were encountered: