B
B
BonBon Slick2021-03-20 02:38:39
Software design
BonBon Slick, 2021-03-20 02:38:39

Update immutable Value Object?

VO update?

class UserName {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function update(string $name): self {
        $copy       = clone $this;
        $copy->name = $name;

        return $copy;
    }

Or so
public function update(string $name): self {
        $new       =  new self($name);
        $new->name = $name;

        return $new;
    }

No matter what update, then
$user->setName($user->name->update('new_name_str'));
...
class User {
    public UserName $name;
...
   public function setName(UserName $name){
        $this->name =  $name;
  }
...


VO is notoriously immutable, so how would you go about updating VO or are you already doing it?

PS I'm doing it right now
class User {
...
   public function setName(string $name){
        $this->name =  new UserName($name);
  }
...


Which approach is more appropriate and why?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question