Skippable fields
I have a problem, when i want exclude sertain fields from serialization. I can provide use case, that helps understand the problem: we have 3-rd party REST API, with PATCH method for updating entities. For example, User class look like this:
class User {
public function __construct(
private ?int $id,
private ?string $firstName,
private ?string $lastName,
) { }
}
If we want to update just first name without knowing last name, we make something like
$user = new User(1, "John", null);
And it serializes in array:
[
'id' => 1,
'first_name' => "John",
'last_name' => null,
]
So, we dont want to update "last_name" field, but we get it in serialization output. We can clean up nulls from resulting array, but then we loose ability to send nulls and we need it, because in other situation, we might want to "clear" our "last_name" by sending null value to that API. I faced this problem in my project and didnt find good solution.
The way i see it, is something like NullObjects, wich can mark fields, that excluded from serialization of some instance. (closed PR with my implementation) In previous case, User class would look like this:
class User {
public function __construct(
private ?int $id,
private string|NullObject|null $firstName,
private string|NullObject|null $lastName,
) { }
}
When we want to update just "first_name":
$user = new User(1, "John", new NullObject);
And it serializes in array:
[
'id' => 1,
'first_name' => "John",
]
I hope i provided enough information to understand the issue.