I have 2 "user" classes which are essentially the same except one is immutable without setters and one is mutable with setters. I have a separate factory for creating each object.
ImmutableUserDto
-ImmutableUserDtoFactory
MutableUserDto
-MutableUserDtoFactory
Both factories take in an array of data and pass it to the class when instantiating it. Then each object class' constructor sets the object from the array passed in, eg:
(simplified code for example)
class MutableUserDtoFactory
{
public function create(array $userData): MutableUserDto
{
return new MutableUserDto($userData);
}
}
class MutableUserDto
{
private $name;
public function __construct($userData)
{
$this->name = $userData['name'];
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
The immutable version is the same except the names start Immutable
and it has no setter.
- Immutable = Data from an API that represents fixed data that should not change, eg display in view, other places, but remain the same for the cycle.
- Mutable = Mostly for forms, add new user or edit user's data.
I dislike that I’m repeating/duplicating the same properties and getters (name, dob, email etc), but moreso am concerned I'm defining the User
model in two places - the Immutable and Mutable object constructors.
If anything changes in the User model, it's defined in (at least) 2 classes that need changing.
Is there a way to somehow abstract some of this into another place? I can't think/find a way, as in the end the two separate classes need to set their own properties which will be the same in both (name, dob, etc).
But am open to ideas, or confirmation that this is just the way it is.