Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skippable fields #47

Open
silenseram opened this issue Apr 3, 2023 · 0 comments
Open

Skippable fields #47

silenseram opened this issue Apr 3, 2023 · 0 comments

Comments

@silenseram
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant