Skip to content

Instantly share code, notes, and snippets.

@MarkRedeman
Last active September 1, 2016 09:49
Show Gist options
  • Select an option

  • Save MarkRedeman/e925b88b709c6ef73ec281b5c003a8af to your computer and use it in GitHub Desktop.

Select an option

Save MarkRedeman/e925b88b709c6ef73ec281b5c003a8af to your computer and use it in GitHub Desktop.
Immutable vs mutable readmodel
<?php
// Immutable
final class Committee
{
private $name;
private $goal;
private $members = [];
public function __construct(string $name, string $goal, array $members)
{
$this->name = $name;
$this->goal = $goal;
$this->members = $members;
}
public function members() : array
{
return $this->members;
}
public function name() : string
{
return $this->name;
}
public function goal() : string
{
return $this->goal;
}
public function changeName(string $name) : Committee
{
return new Committee($name, $this->goal, $this->members);
}
public function changeGoal(string $goal) : Committee
{
return new Committee($this->name, $goal, $this->members);
}
public function addMember(MemberId $memberId, string $firstName, string $lastName) : Committee
{
return new Committee(
$this->name,
$this->goal,
array_merge(
$this->members,
[[
"id" => (string)$memberId,
"firstName" => $firstName,
"lastName" => $lastName
]]
)
);
}
public function removeMember(MemberId $id) : Committee
{
return new Committee(
$this->name,
$this->goal,
array_filter(
$this->members,
function (array $member) use ($id) {
return ! ($member['id'] == (string)$id);
}
)
);
}
}
<?php
// Mutable
final class Committee
{
private $name;
private $goal;
private $members = [];
public function __construct(string $name, string $goal)
{
$this->name = $name;
$this->goal = $goal;
}
public function members() : array
{
return $this->members;
}
public function name() : string
{
return $this->name;
}
public function goal() : string
{
return $this->goal;
}
public function changeName(string $name)
{
$this->name = $name;
}
public function changeGoal(string $goal)
{
$this->goal = $goal;
}
public function addMember(MemberId $memberId, string $firstName, string $lastName)
{
$this->members[] = [
"id" => (string)$memberId,
"firstName" => $firstName,
"lastName" => $lastName
];
}
public function removeMember(MemberId $id)
{
$this->members = array_filter(
$this->members,
function (array $member) use ($id) {
return ! ($member['id'] == (string)$id);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment