Skip to content

Add ComparableData trait with equalTo() method for value comparison #999

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

Closed

Conversation

clementbirkle
Copy link
Contributor

This PR adds a new ComparableData trait and interface that provides an equalTo() method to compare data objects by their values rather than their instances.

Why?

PHP's default object comparison operator == only checks if two objects are the same instance. This limitation becomes particularly problematic when data objects contain special properties like Optional attributes.

This new equalTo() method allows comparing data objects based on their values by comparing the result of their toArray() methods, which correctly handles nested objects, collections, and special types like Optional.

Usage Example

class UserData extends Data
{
    public function __construct(
        public int $id,
        public string|Optional $name = new Optional,
    ) {}
}

$data1 = new UserData(id: 10);
$data2 = UserData::from($data1);

// Default PHP comparison (checks object instance)
$data1 == $data2; // false (different instances)

// New value comparison (checks actual values)
$data1->equalTo($data2); // true (same values)

// When values differ
$data2->name = 'John';
$data1->equalTo($data2); // false (different values)

This method is especially useful in testing scenarios or when comparing objects from different sources, including comparing objects with nested data structures or optional properties.

@rubenvanassche
Copy link
Member

Thanks for your PR, while this might be useful in some cases. It can be a heavy operation to always convert a whole structure to an array for a simple == operation. It is up to the developer in my opinion to write such logic for data objects which can be written smarter. As long as PHP doesn't have operator overloading built in I don't think we want to dive into pandora's box of comparing data objects. You're always welcome to package up your work and I'll gladly link to it in the docs.

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

Successfully merging this pull request may close these issues.

2 participants