クソコード動画「カプセル化」 pic.twitter.com/kAhXCEHYVT
— ミノ駆動 (@MinoDriven) June 23, 2019
もくじ
問題
- データが書き換わってしまってしまう。
対応
- イミュータブルにする
- getter/setterをつくらない
ミュータブル(可変)
client.php
<?php
require_once('mmutable.php');
$pokemon = new Pokemon('ミュウ');
$pokemon->setName('ピカチュー');
echo $pokemon->getName(); // ピカチュー
mmutable.php
<?php
final class Pokemon
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
}
実行結果
ピカチュー
上書きされてしまっている。
イミュータブル(不変)
client.php
<?php
require_once('immutable.php');
$pokemon = new Pokemon('ミュウ');
$pokemon->setName('ピカチュー');
echo $pokemon->getName(); // ミュウ
immutable.php
<?php
final class Pokemon
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
//public function setName(string $name): self
//{
// return new self($name);
//}
public function setName(string $name): self
{
$new = clone $this;
$new->name = $name;
return $new;
}
}
実行結果
ミュウ
書き変わらない。
![PHP Template Methodパターン [PHPによるデザインパターン入門]](https://www.yuulinux.tokyo/contents/wp-content/uploads/2017/09/phpDP_20190407_1-150x150.jpg)
