アプリケーションサービスを簡単に説明するとユースケースを実現するオブジェクト
例えば、ユーザー登録が必要なシステムに置いて、ユーザー機能を実現するには「ユーザーを登録する」ユースケースや、「ユーザー情報を変更する」ユースケースが必要。なのでアプリケーションサービスにはそのような振る舞いを定義する必要がある
SNSのユーザー機能を題材としてアプリケーションサービスのユースケースを考える
ユーザー機能に必要なユースケース
まず、アプリケーションサービスが取り扱うドメインオブジェクトを準備する必要がある
ユーザーの概念はライフサイクルがあるのでエンティティとして実装する
(例)ユーザーを表すエンティティ
class User
{
private UserId $id;
private UserName $name;
public function __construct(UserName $name, UserId $id = null)
{
if (
$id === null ||
$name === null
) throw new ErrorException('引数がnullです。');
$this->id = $id;
$this->name = $name;
}
public function getId()
{
return $this->id->getUserId();
}
public function getName()
{
return $this->name->getUserName();
}
public function changeName(UserName $name)
{
if ($name === null) throw new ErrorException('引数がnullです。');
if (mb_strlen($name) < 3) throw new ErrorException('ユーザー名は3文字以上です。');
$this->name = $name;
}
}
Userには同一性を識別するためのUserIdという識別子が定義されており、UserIDとUserNameは値オブジェクトとして定義する
(例)Userクラスが利用している値オブジェクトの定義
class UserId
{
private int $userId;
public function __construct(int $userId)
{
if ($userId === null) throw new ErrorException('引数がnullです。');
$this->userId = $userId;
}
public function getUserId(): int
{
return $this->userId;
}
}
class UserName
{
private string $userName;
public function __construct(string $userName)
{
if ($userName === null) throw new ErrorException('引数がnullです。');
if ($userName < 3) throw new ErrorException('ユーザー名が3文字以下です。');
$this->userName = $userName;
}
public function getUserName(): string
{
return $this->userName;
}
}
また、ユーザーの重複がないことを確認する必要がある。この処理はドメインサービスとして用意する