Share
Embed
ドメインイベントを活用したPHPコードのリファクタリング
PHPerKaigi 2025の登壇資料です。
https://fortee.jp/phperkaigi-2025/proposal/5615c479-cc86-42db-b6b8-d3879e557a3e
みなさん、ドメインイベントって使っていますか?
このトークでは、ドメインイベントを使ってPHPコードをリファクタリングする方法についてお話しします。
ドメインイベントは、ビジネスドメインで発生する「出来事」を表現するモデルです。注文の完了やユーザー登録のようなビジネスプロセスの特定の状態変化を表現できます。
これをうまく使うことで、副作用をわかりやすく整理し、システムをシンプルにできます。
ドメインイベントを導入してみると、「あ、こんな風に設計すれば良いんだ!」と新しい発見があるはずです。リファクタリングを通じて、どうやってドメインイベントを設計し、活用するのか、その具体的な手法をお伝えします!
参考:
『実践ドメイン駆動設計』Vaughn Vernon著
TechTrain: https://service.techtrain.dev/
Takuma Kajikawa
March 21, 2025
Transcript
34 slides
-
肥大化していくコード ユーザー時に色々やりたい 1クラスに多くの責務が集中 テストも複雑になりがち(副作用の数だけモックが必要) 責務が混在し、変更の影響範囲が予測しづらい class UserController { public function
create($userData) { // DB に保存 // 副作用1 メール送信 // 副作用2 運営に通知 // 副作用3 契約プランの作成 // 副作用4 招待コード利用処理 // 副作用5 関連サービスへの連携 // etc... } } 3/34 -
実装すると... class UserController { private $userRepository; private $mailService; private $notificationService;
private $planService; private $invitationService; private $externalService; public function create($userData) { try { // バリデーション $this->validateUserData($userData); // DB 保存 $user = new User(); $user->setEmail($userData['email']); $user->setName($userData['name']); $user->setPassword(password_hash($userData['password'], PASSWORD_DEFAULT)); $this->userRepository->save($user); // メール送信 $this->mailService->sendWelcomeEmail([ 'to' => $user->getEmail(), 'name' => $user->getName() ]); // 運営に通知 $this->notificationService->notifyToAdmin([ 'message' => " 新規ユーザー作成: {$user->getName()}", 'channel' => 'user-Create' ]); // 契約プランの作成 $plan = $this->planService->createFreePlan($user->getId()); // 招待コードがある場合の処理 if (isset($userData['invitation_code'])) { $this->invitationService->markAsUsed($userData['invitation_code'], $user->getId()); // 紹介者にポイント付与 $inviter = $this->invitationService->getInviter($userData['invitation_code']); $this->planService->addReferralPoints($inviter->getId(), 1000); } // 関連サービスへの連携 $this->externalService->syncUser([ 'user_id' => $user->getId(), 'email' => $user->getEmail(), 'name' => $user->getName() ]); return $user; } catch (ValidationException $e) { throw new UserCreateException(' 入力データが不正です: ' . $e->getMessage()); } catch (DatabaseException $e) { // メール送信のロールバックなど throw new UserCreateException(' ユーザー作成に失敗しました: ' . $e->getMessage()); } catch (Exception $e) { // その他のエラーハンドリング throw new UserCreateException(' 予期せぬエラーが発生しました: ' . $e->getMessage()); } } private function validateUserData($userData) { if (empty($userData['email']) || !filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) { throw new ValidationException(' メールアドレスが不正です'); } if (empty($userData['name']) || strlen($userData['name']) < 3) { throw new ValidationException(' 名前は3 文字以上で入力してください'); } if (empty($userData['password']) || strlen($userData['password']) < 8) { throw new ValidationException(' パスワードは8 文字以上で入力してください'); } } 4/34 -
ユースケース (Before) // ユーザー作成メソッドの一部 class UserCreateUsecase { public function create(Request
$request) { // 1) ユーザー情報をDB に保存 $user = new UserModel(); $user->id = Uuid::generate(); $user->email = $request->input('email'); $user->save(); // 2) ウェルカムメール送信 $mailService = new MailService(); $mailService->sendWelcomeMail($user->email); // 3) 初期ポイント付与 $pointService = new PointService(); $pointService->addInitialPoints($user->id); // その他の処理がどんどん増える... return response()->json(['status' => 'success']); } } 19/34 -
ユースケースとドメインイベント (After) class UserCreateUsecase { public function exec(UserId $userId, Email
$email): void { // ドメインモデルを生成(ここでイベントが内部的に作成される) $user = User::create($userId, $email); DB::transaction(function () use ($user) { // リポジトリに保存 $this->userRepository->create($user, $eventPublisher); }); } } class UserRepository { public function create(User $user, UserCreatedEventPublisher $eventPublisher): void { // 永続化 // ドメインイベントを発行 foreach ($user->pullDomainEvents() as $event) { $this->eventPublisher->publish($event); } } } 20/34 -
テストも書きやすく // ユースケースでは実行時にイベント発行されるかをテストする final class UserCreateUsecaseTest extends TestCase { #[Test]
public function ユーザーを作成する() { // イベント発行をモック $this->mock(DomainEventPublisher::class) ->expects($this->once()) ->method('publish'); // 切り出した処理のみに集中してテストする final class WelcomeMailSubscriberTest extends TestCase { #[Test] public function ユーザー作成時にウェルカムメールを送信する(): void { $mailService = $this->mock(MailService::class); $mailService->expects($this->once()) ->method('sendWelcomeMail') ->with($this->equalTo(new Email('[email protected]'))); $event = new UserCreatedEvent(new UserId('123'), new Email('[email protected]')); 21/34 -
ドメインモデルがドメインイベントを作成する まだ実行はされない class User implements IDomainEventStorable { use DomainEventStorable; public
static function create(UserId $userId, Email $email): self { $user = new self($userId, $email); // ドメインイベントを内部に保持 $user->pushDomainEvent(new UserCreatedEvent($userId, $email)); return $user; } } 22/34 -
DomainEventPublisher パブリッシャーにはサブスクライバ(処理したい内容)とドメインイベントを発行する機能を持たせる ここでpublishすると実行される final class UserCreatedEventPublisher { public function __construct(
SendWelcomeMailSubscriber $mailSubscriber, CreateStripeCustomerSubscriber $stripeSubscriber, SendSlackMessageSubscriber $slackSubscriber, ) { // コンストラクタでsubscribers に追加する } public function publish(DomainEvent $event): void { foreach ($this->subscribers as $subscriber) { $subscriber->handle($event); } } } 23/34 -
DomainEventSubscriberには切り出した処理の内容を書 く class WelcomeMailSubscriber { public function handle(UserCreatedEvent $event): void
{ // イベントに応じた処理を実行 $this->mailService->sendWelcomeMail($event->email()); } } 24/34 -
非同期処理での全体像 メッセージングサービスを活用した非同期処理の手法は他にもあるので一例として 1. ドメインモデルがドメインイベントを作成 2. アプリケーションレイヤーでドメインイベントをPublish 3. PublishされたイベントをDBに保存 4. バッチ処理で未処理のドメインイベントをメッセージングサービスにPublish
5. メッセージングサービスからSubscribeしたイベントに対応する処理を行う 非同期になってもドメインイベント自体の処理は変わらない 28/34 -
メッセージングサービスへの保存 class EventStore { public function save(DomainEvent $event): void {
$stmt = $this->pdo->prepare( 'INSERT INTO event_store ( event_id, event_type, aggregate_id, payload, status, created_at ) VALUES (?, ?, ?, ?, ?, ?)' ); $stmt->execute([ Uuid::generate(), get_class($event), $event->aggregateId(), json_encode($event->toArray()), 'pending', // 未処理状態 new DateTimeImmutable() ]); } public function findUnprocessedEvents(int $limit = 100): array {} public function markAsProcessed(string $eventId): void {} } 29/34 -
バッチ処理の実装 class PublishPendingEventsCommand { public function handle(): void { $events
= $this->eventStore->findUnprocessedEvents(); foreach ($events as $event) { // メッセージングサービスにパブリッシュ $this->queueClient->publish( 'user_events', json_encode([ 'id' => $event['event_id'], 'event_type' => $event['event_type'], 'payload' => json_decode($event['payload'], true), 'created_at' => $event['created_at'] ]) ); // 処理済みとしてマーク $this->eventStore->markAsProcessed($event['event_id']); } } 30/34 -
メッセージングサービスからのイベント処理 1. イベントを受け取るエンドポイント class UserEventController { public function onCreated(Request $request):
Response { $payload = $request->json()->all(); // イベントの復元 $event = $this->restoreEvent($payload); // イベントに対応するハンドラを取得 $handler = $this->resolver->resolve($event); // イベントの処理を実行 $handler->handle($event); // 処理済みとしてマーク $this->processedEventStore->markAsProcessed($eventId); } } 31/34