Мини-проект: доменная модель BackendStart
За предыдущие уроки мы разобрали каждый строительный блок DDD Lite по отдельности. Теперь соберём их вместе в единую рабочую модель для реального проекта - образовательной платформы BackendStart.
Цель: пользователь проходит уроки, решает квизы, видит свой прогресс по курсу. Когда все уроки пройдены - курс завершён.
Ubiquitous Language: словарь проекта
Прежде чем писать код, зафиксируем единый язык. Порядок именно такой не случайно: словарь пишется до кода, иначе термины расползутся по слоям в трёх вариантах - почему это работает так и как поддерживать словарь живым, в уроке Ubiquitous Language. Каждый термин имеет ровно одно значение во всём контексте Learning:
| Термин | Определение |
|---|---|
| Track | Направление обучения (Go, Docker, DDD). Содержит курсы |
| Course | Набор уроков по одной теме внутри трека |
| Lesson | Единица обучения: markdown-контент + опциональный квиз |
| Quiz | Набор вопросов к уроку. Считается пройденным, если Score не ниже проходного балла (в мини-проекте 70%; на самой BackendStart сейчас 100%) |
| CourseProgress | Состояние прохождения курса конкретным пользователем |
| LessonProgress | Статус одного урока внутри прогресса курса |
| Completed | Урок пройден: контент прочитан и квиз сдан (если есть) |
| CourseFinished | Все уроки курса в статусе Completed |
В мини-проекте модель шире, чем в глоссарии урока Ubiquitous Language: там курс и трек совпадали, а здесь трек объединяет несколько курсов. Когда модель так меняется, глоссарий правят вместе с кодом, а не держат два определения одного слова.
ℹ️ Словарь - живой документ
Ubiquitous Language обновляется вместе с проектом. Если бизнес начинает говорить "модуль" вместо "урок" - код должен измениться тоже. Расхождение между речью и кодом - источник багов.
Структура пакетов
Проект организован по гексагональной архитектуре внутри Bounded Context learning:
internal/learning/
domain/
course.go # Entity: Course, Lesson
progress.go # Aggregate: CourseProgress + LessonProgress
value_objects.go # VO: CourseSlug, LessonSlug, Email, QuizScore
events.go # Domain Events
repository.go # Repository interfaces
quiz_evaluator.go # Domain Service
app/
complete_lesson.go # Use-case: CompleteLessonUseCase
start_course.go # Use-case: StartCourseUseCase
infra/
gorm_progress.go # GORM-реализация ProgressRepository
gorm_course.go # GORM-реализация CourseRepository
event_publisher.go # InMemoryPublisher
handlers/
grant_certificate.go
update_stats.go
Правило: domain/ не импортирует ничего из app/ и infra/. app/ не импортирует infra/. Зависимости направлены только внутрь.
Имена каталогов здесь в словаре DDD: app/ - слой приложения, infra/ - инфраструктура. В треке Hexagonal Architecture те же слои называются usecase/ и adapters/, а интерфейс репозитория лежит не в domain/, а в usecase/ports/. Оба варианта держат интерфейс внутри, а реализацию снаружи; разница разобрана во врезке урока Репозитории и интерфейсы.
Value Objects
Value Object не имеет идентичности. Два объекта с одинаковыми значениями равны. Валидация - в конструкторе. Если признаки объекта-значения и способ отличить его от сущности успели выветриться, они собраны в уроке Entity и Value Object:
package domain
import (
"fmt"
"regexp"
"strings"
)
// Упрощение: VO здесь - определяемые типы, и конверсия CourseSlug("...")
// или QuizScore(500) обходит конструктор. В продакшене - структура
// с приватным полем, как Email в уроке Entity и Value Object.
// CourseSlug - URL-безопасный идентификатор курса
type CourseSlug string
var slugRegex = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*
Мини-проект: доменная модель BackendStart (Course/Lesson/Progress) | BackendStart.ru
)
func NewCourseSlug(raw string) (CourseSlug, error) {
s := strings.TrimSpace(strings.ToLower(raw))
if !slugRegex.MatchString(s) {
return "", fmt.Errorf("invalid course slug: %q", raw)
}
return CourseSlug(s), nil
}
func (s CourseSlug) String() string { return string(s) }
// LessonSlug - URL-безопасный идентификатор урока
type LessonSlug string
func NewLessonSlug(raw string) (LessonSlug, error) {
s := strings.TrimSpace(strings.ToLower(raw))
if !slugRegex.MatchString(s) {
return "", fmt.Errorf("invalid lesson slug: %q", raw)
}
return LessonSlug(s), nil
}
func (s LessonSlug) String() string { return string(s) }
// Email пользователя
type Email string
func NewEmail(raw string) (Email, error) {
trimmed := strings.TrimSpace(raw)
if !strings.Contains(trimmed, "@") || len(trimmed) < 5 {
return "", fmt.Errorf("invalid email: %q", raw)
}
return Email(strings.ToLower(trimmed)), nil
}
// QuizScore - результат квиза (0..100)
type QuizScore int
func NewQuizScore(val int) (QuizScore, error) {
if val < 0 || val > 100 {
return 0, fmt.Errorf("quiz score must be 0..100, got %d", val)
}
return QuizScore(val), nil
}
func (s QuizScore) Passed() bool { return int(s) >= 70 }
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
use InvalidArgumentException;
// CourseSlug - URL-безопасный идентификатор курса
final readonly class CourseSlug
{
private const PATTERN = '/^[a-z0-9]+(-[a-z0-9]+)*$/';
private function __construct(private string $value) {}
public static function fromString(string $raw): self
{
$s = strtolower(trim($raw));
if (preg_match(self::PATTERN, $s) !== 1) {
throw new InvalidArgumentException('invalid course slug: ' . $raw);
}
return new self($s);
}
public function value(): string { return $this->value; }
public function equals(self $other): bool { return $this->value === $other->value; }
public function __toString(): string { return $this->value; }
}
// LessonSlug - URL-безопасный идентификатор урока
final readonly class LessonSlug
{
private const PATTERN = '/^[a-z0-9]+(-[a-z0-9]+)*$/';
private function __construct(private string $value) {}
public static function fromString(string $raw): self
{
$s = strtolower(trim($raw));
if (preg_match(self::PATTERN, $s) !== 1) {
throw new InvalidArgumentException('invalid lesson slug: ' . $raw);
}
return new self($s);
}
public function value(): string { return $this->value; }
public function equals(self $other): bool { return $this->value === $other->value; }
public function __toString(): string { return $this->value; }
}
// Email пользователя
final readonly class Email
{
private function __construct(private string $value) {}
public static function fromString(string $raw): self
{
$trimmed = trim($raw);
if (!str_contains($trimmed, '@') || strlen($trimmed) < 5) {
throw new InvalidArgumentException('invalid email: ' . $raw);
}
return new self(strtolower($trimmed));
}
public function value(): string { return $this->value; }
public function equals(self $other): bool { return $this->value === $other->value; }
}
// QuizScore - результат квиза (0..100)
final readonly class QuizScore
{
private function __construct(private int $value) {}
public static function fromInt(int $val): self
{
if ($val < 0 || $val > 100) {
throw new InvalidArgumentException(
sprintf('quiz score must be 0..100, got %d', $val)
);
}
return new self($val);
}
public function value(): int { return $this->value; }
public function passed(): bool { return $this->value >= 70; }
public function equals(self $other): bool { return $this->value === $other->value; }
}
import re
from dataclasses import dataclass
_SLUG_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*quot;)
class CourseSlug(str):
"""URL-безопасный идентификатор курса.
Подкласс str: иммутабелен, сравнивается по значению, валидация в конструкторе.
"""
__slots__ = ()
def __new__(cls, raw: str) -> "CourseSlug":
s = raw.strip().lower()
if not _SLUG_RE.match(s):
raise ValueError(f"invalid course slug: {raw!r}")
return super().__new__(cls, s)
class LessonSlug(str):
"""URL-безопасный идентификатор урока."""
__slots__ = ()
def __new__(cls, raw: str) -> "LessonSlug":
s = raw.strip().lower()
if not _SLUG_RE.match(s):
raise ValueError(f"invalid lesson slug: {raw!r}")
return super().__new__(cls, s)
@dataclass(frozen=True)
class Email:
"""Email пользователя - VO как в уроке про Entity и Value Object.
Слаги выше - подклассы str ради ключей словарей и URL; у Email
есть поведение и нормализация, поэтому он frozen dataclass.
"""
value: str
def __post_init__(self) -> None:
trimmed = self.value.strip()
if "@" not in trimmed or len(trimmed) < 5:
raise ValueError(f"invalid email: {self.value!r}")
# frozen запрещает self.value = ..., нормализованное значение кладём напрямую
object.__setattr__(self, "value", trimmed.lower())
def __str__(self) -> str:
return self.value
class QuizScore(int):
"""Результат квиза (0..100)."""
__slots__ = ()
def __new__(cls, val: int) -> "QuizScore":
if val < 0 or val > 100:
raise ValueError(f"quiz score must be 0..100, got {val}")
return super().__new__(cls, val)
def passed(self) -> bool:
return self >= 70
Entities: Course и Lesson
Entity имеет уникальный идентификатор. Два Course с одинаковым названием, но разным ID - разные объекты:
package domain
type CourseID int64
type LessonID int64
type Course struct {
ID CourseID
Title string
Slug CourseSlug
TrackSlug string
Lessons []Lesson
Description string
}
func (c *Course) TotalLessons() int {
return len(c.Lessons)
}
func (c *Course) FindLesson(slug LessonSlug) (Lesson, bool) {
for _, l := range c.Lessons {
if l.Slug == slug {
return l, true
}
}
return Lesson{}, false
}
type Lesson struct {
ID LessonID
Title string
Slug LessonSlug
Order int
HasQuiz bool
}
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
// Course - Entity. Поведение внутри: TotalLessons, FindLesson.
final class Course
{
/** @param Lesson[] $lessons */
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly CourseSlug $slug,
public readonly string $trackSlug,
public readonly array $lessons,
public readonly string $description,
) {}
public function totalLessons(): int
{
return count($this->lessons);
}
public function findLesson(LessonSlug $slug): ?Lesson
{
foreach ($this->lessons as $l) {
if ($l->slug->equals($slug)) {
return $l;
}
}
return null;
}
}
// Lesson - Entity внутри Course.
final readonly class Lesson
{
public function __construct(
public int $id,
public string $title,
public LessonSlug $slug,
public int $order,
public bool $hasQuiz,
) {}
}
from dataclasses import dataclass
from typing import NewType
CourseID = NewType("CourseID", int)
LessonID = NewType("LessonID", int)
@dataclass(frozen=True, slots=True)
class Lesson:
"""Entity внутри Course."""
lesson_id: LessonID
title: str
slug: LessonSlug
order: int
has_quiz: bool
@dataclass(slots=True)
class Course:
"""Entity. Поведение внутри: total_lessons, find_lesson."""
course_id: CourseID
title: str
slug: CourseSlug
track_slug: str
lessons: list[Lesson]
description: str
def total_lessons(self) -> int:
return len(self.lessons)
def find_lesson(self, slug: LessonSlug) -> Lesson | None:
for lesson in self.lessons:
if lesson.slug == slug:
return lesson
return None
Aggregate: CourseProgress
CourseProgress - агрегат (корень) с дочерними LessonProgress. Все изменения идут через корень, он следит за инвариантами и собирает события:
package domain
import (
"fmt"
"time"
)
// Поля закрыты, как в уроке про агрегаты: менять состояние можно только
// методами корня, которые держат инварианты.
type CourseProgress struct {
id int64
userID int64
courseSlug CourseSlug
lessons []LessonProgress
percent int
startedAt time.Time
events []interface{}
}
type LessonProgress struct {
lessonSlug LessonSlug
hasQuiz bool // копия Lesson.HasQuiz: нужна правилу Completed
completed bool
quizScore *QuizScore
completedAt *time.Time
}
// Геттеры только читают. Lessons отдаёт копию: изменить урок в обход
// CompleteLesson через возвращённый срез нельзя.
func (p *CourseProgress) ID() int64 { return p.id }
func (p *CourseProgress) UserID() int64 { return p.userID }
func (p *CourseProgress) CourseSlug() CourseSlug { return p.courseSlug }
func (p *CourseProgress) Percent() int { return p.percent }
func (p *CourseProgress) StartedAt() time.Time { return p.startedAt }
func (p *CourseProgress) Lessons() []LessonProgress {
return append([]LessonProgress(nil), p.lessons...)
}
func (lp LessonProgress) LessonSlug() LessonSlug { return lp.lessonSlug }
func (lp LessonProgress) HasQuiz() bool { return lp.hasQuiz }
func (lp LessonProgress) Completed() bool { return lp.completed }
func (lp LessonProgress) QuizScore() *QuizScore { return lp.quizScore }
func (lp LessonProgress) CompletedAt() *time.Time { return lp.completedAt }
// RestoreCourseProgress собирает агрегат из сохранённых данных - им
// пользуется репозиторий. Восстановление воспроизводит прошлое состояние,
// а не создаёт новое, поэтому правила NewCourseProgress здесь не нужны.
func RestoreCourseProgress(id, userID int64, slug CourseSlug, lessons []LessonProgress, startedAt time.Time) *CourseProgress {
p := &CourseProgress{id: id, userID: userID, courseSlug: slug, lessons: lessons, startedAt: startedAt}
p.recalcPercent() // процент - производное значение, его не доверяют базе
return p
}
// RestoreLessonProgress - то же для урока внутри агрегата.
func RestoreLessonProgress(slug LessonSlug, hasQuiz, completed bool, score *QuizScore, completedAt *time.Time) LessonProgress {
return LessonProgress{lessonSlug: slug, hasQuiz: hasQuiz, completed: completed, quizScore: score, completedAt: completedAt}
}
func NewCourseProgress(userID int64, course Course) *CourseProgress {
lessons := make([]LessonProgress, 0, len(course.Lessons))
for _, l := range course.Lessons {
lessons = append(lessons, LessonProgress{
lessonSlug: l.Slug,
hasQuiz: l.HasQuiz,
})
}
return &CourseProgress{
userID: userID,
courseSlug: course.Slug,
lessons: lessons,
percent: 0,
startedAt: time.Now(),
}
}
// CompleteLesson отмечает урок пройденным и генерирует события
func (p *CourseProgress) CompleteLesson(slug LessonSlug) error {
idx := p.findLessonIndex(slug)
if idx == -1 {
return fmt.Errorf("lesson %s not found in course %s", slug, p.courseSlug)
}
if p.lessons[idx].completed {
return nil // идемпотентность: повторный вызов не ошибка
}
// Правило из словаря: урок с квизом Completed только после сдачи квиза
if lp := p.lessons[idx]; lp.hasQuiz && (lp.quizScore == nil || !lp.quizScore.Passed()) {
return fmt.Errorf("lesson %s: quiz not passed", slug)
}
now := time.Now()
p.lessons[idx].completed = true
p.lessons[idx].completedAt = &now
p.recalcPercent()
p.collectEvent(LessonCompleted{
UserID: p.userID,
CourseSlug: p.courseSlug.String(),
LessonSlug: slug.String(),
OccurredAt: now,
})
if p.percent == 100 {
p.collectEvent(CourseFinished{
UserID: p.userID,
CourseSlug: p.courseSlug.String(),
OccurredAt: now,
})
}
return nil
}
// RecordQuizScore сохраняет результат квиза для урока
func (p *CourseProgress) RecordQuizScore(slug LessonSlug, score QuizScore) error {
idx := p.findLessonIndex(slug)
if idx == -1 {
return fmt.Errorf("lesson %s not found in course %s", slug, p.courseSlug)
}
p.lessons[idx].quizScore = &score
if score.Passed() {
p.collectEvent(QuizPassed{
UserID: p.userID,
LessonSlug: slug.String(),
Score: int(score),
OccurredAt: time.Now(),
})
}
return nil
}
func (p *CourseProgress) findLessonIndex(slug LessonSlug) int {
for i, lp := range p.lessons {
if lp.lessonSlug == slug {
return i
}
}
return -1
}
func (p *CourseProgress) recalcPercent() {
if len(p.lessons) == 0 {
p.percent = 0
return
}
completed := 0
for _, lp := range p.lessons {
if lp.completed {
completed++
}
}
p.percent = completed * 100 / len(p.lessons)
}
func (p *CourseProgress) collectEvent(e interface{}) {
p.events = append(p.events, e)
}
func (p *CourseProgress) FlushEvents() []interface{} {
events := p.events
p.events = nil
return events
}
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
use DateTimeImmutable;
use DomainException;
// LessonProgress - внутренний объект агрегата.
// Изменяемый: completed и quizScore меняются.
final class LessonProgress
{
public function __construct(
public readonly LessonSlug $lessonSlug,
public readonly bool $hasQuiz = false, // копия Lesson::hasQuiz: нужна правилу Completed
private bool $completed = false,
private ?QuizScore $quizScore = null,
private ?DateTimeImmutable $completedAt = null,
) {}
public function isCompleted(): bool { return $this->completed; }
public function quizScore(): ?QuizScore { return $this->quizScore; }
public function markCompleted(DateTimeImmutable $at): void
{
$this->completed = true;
$this->completedAt = $at;
}
public function setQuizScore(QuizScore $score): void
{
$this->quizScore = $score;
}
}
// CourseProgress - Aggregate Root. НЕ readonly: мутируется.
final class CourseProgress
{
/**
* @param LessonProgress[] $lessons
* @param object[] $events
*/
public function __construct(
public readonly int $id,
public readonly int $userId,
public readonly CourseSlug $courseSlug,
private array $lessons,
private int $percent,
public readonly DateTimeImmutable $startedAt,
private array $events = [],
) {}
public static function start(int $userId, Course $course): self
{
$lessons = [];
foreach ($course->lessons as $l) {
$lessons[] = new LessonProgress(lessonSlug: $l->slug, hasQuiz: $l->hasQuiz);
}
return new self(
id: 0,
userId: $userId,
courseSlug: $course->slug,
lessons: $lessons,
percent: 0,
startedAt: new DateTimeImmutable(),
);
}
public function percent(): int { return $this->percent; }
/** @return LessonProgress[] */
public function lessons(): array { return $this->lessons; }
// completeLesson отмечает урок пройденным и генерирует события
public function completeLesson(LessonSlug $slug): void
{
$idx = $this->findLessonIndex($slug);
if ($idx === null) {
throw new DomainException(sprintf(
'lesson %s not found in course %s',
$slug,
$this->courseSlug,
));
}
$lp = $this->lessons[$idx];
if ($lp->isCompleted()) {
return; // идемпотентность: повторный вызов не ошибка
}
// Правило из словаря: урок с квизом Completed только после сдачи квиза
if ($lp->hasQuiz && ($lp->quizScore() === null || !$lp->quizScore()->passed())) {
throw new DomainException(sprintf('lesson %s: quiz not passed', $slug));
}
$now = new DateTimeImmutable();
$this->lessons[$idx]->markCompleted($now);
$this->recalcPercent();
$this->recordEvent(new LessonCompleted(
userId: $this->userId,
courseSlug: $this->courseSlug->value(),
lessonSlug: $slug->value(),
occurredAt: $now,
));
if ($this->percent === 100) {
$this->recordEvent(new CourseFinished(
userId: $this->userId,
courseSlug: $this->courseSlug->value(),
occurredAt: $now,
));
}
}
// recordQuizScore сохраняет результат квиза для урока
public function recordQuizScore(LessonSlug $slug, QuizScore $score): void
{
$idx = $this->findLessonIndex($slug);
if ($idx === null) {
throw new DomainException(sprintf(
'lesson %s not found in course %s',
$slug,
$this->courseSlug,
));
}
$this->lessons[$idx]->setQuizScore($score);
if ($score->passed()) {
$this->recordEvent(new QuizPassed(
userId: $this->userId,
lessonSlug: $slug->value(),
score: $score->value(),
occurredAt: new DateTimeImmutable(),
));
}
}
private function findLessonIndex(LessonSlug $slug): ?int
{
foreach ($this->lessons as $i => $lp) {
if ($lp->lessonSlug->equals($slug)) {
return $i;
}
}
return null;
}
private function recalcPercent(): void
{
$total = count($this->lessons);
if ($total === 0) {
$this->percent = 0;
return;
}
$completed = 0;
foreach ($this->lessons as $lp) {
if ($lp->isCompleted()) {
$completed++;
}
}
$this->percent = intdiv($completed * 100, $total);
}
private function recordEvent(object $e): void
{
$this->events[] = $e;
}
/** @return object[] */
public function pullEvents(): array
{
$events = $this->events;
$this->events = [];
return $events;
}
}
from dataclasses import dataclass, field, replace
from datetime import datetime
class DomainError(Exception):
"""Нарушение правил домена."""
@dataclass(slots=True)
class LessonProgress:
"""Внутренний объект агрегата.
Изменяемый: completed и quiz_score меняются.
"""
lesson_slug: LessonSlug
has_quiz: bool = False # копия Lesson.has_quiz: нужна правилу Completed
completed: bool = False
quiz_score: QuizScore | None = None
completed_at: datetime | None = None
@dataclass
class CourseProgress:
"""Aggregate Root. Мутируется, поэтому не frozen.
Изменяемое состояние (_lessons, _percent) закрыто подчёркиванием, как
в уроке про агрегаты: менять его можно только методами корня. Снаружи -
свойства только для чтения.
"""
progress_id: int
user_id: int
course_slug: CourseSlug
_lessons: list[LessonProgress]
_percent: int = 0
started_at: datetime = field(default_factory=datetime.now)
_events: list[object] = field(default_factory=list, repr=False)
@property
def percent(self) -> int:
return self._percent
@property
def lessons(self) -> tuple[LessonProgress, ...]:
# Копии: изменить урок в обход complete_lesson через них нельзя.
return tuple(replace(lp) for lp in self._lessons)
@classmethod
def start(cls, user_id: int, course: Course) -> "CourseProgress":
lessons = [
LessonProgress(lesson_slug=lesson.slug, has_quiz=lesson.has_quiz)
for lesson in course.lessons
]
return cls(
progress_id=0,
user_id=user_id,
course_slug=course.slug,
_lessons=lessons,
_percent=0,
started_at=datetime.now(),
)
def complete_lesson(self, slug: LessonSlug) -> None:
"""Отмечает урок пройденным и генерирует события."""
idx = self._find_lesson_index(slug)
if idx == -1:
raise DomainError(f"lesson {slug} not found in course {self.course_slug}")
lp = self._lessons[idx]
if lp.completed:
return # идемпотентность: повторный вызов не ошибка
# Правило из словаря: урок с квизом Completed только после сдачи квиза
if lp.has_quiz and (lp.quiz_score is None or not lp.quiz_score.passed()):
raise DomainError(f"lesson {slug}: quiz not passed")
now = datetime.now()
self._lessons[idx].completed = True
self._lessons[idx].completed_at = now
self._recalc_percent()
self._collect_event(LessonCompleted(
user_id=self.user_id,
course_slug=str(self.course_slug),
lesson_slug=str(slug),
occurred_at=now,
))
if self._percent == 100:
self._collect_event(CourseFinished(
user_id=self.user_id,
course_slug=str(self.course_slug),
occurred_at=now,
))
def record_quiz_score(self, slug: LessonSlug, score: QuizScore) -> None:
"""Сохраняет результат квиза для урока."""
idx = self._find_lesson_index(slug)
if idx == -1:
raise DomainError(f"lesson {slug} not found in course {self.course_slug}")
self._lessons[idx].quiz_score = score
if score.passed():
self._collect_event(QuizPassed(
user_id=self.user_id,
lesson_slug=str(slug),
score=int(score),
occurred_at=datetime.now(),
))
def _find_lesson_index(self, slug: LessonSlug) -> int:
for i, lp in enumerate(self._lessons):
if lp.lesson_slug == slug:
return i
return -1
def _recalc_percent(self) -> None:
if not self._lessons:
self._percent = 0
return
completed = sum(1 for lp in self._lessons if lp.completed)
self._percent = completed * 100 // len(self._lessons)
def _collect_event(self, event: object) -> None:
self._events.append(event)
def flush_events(self) -> list[object]:
events = self._events
self._events = []
return events
⚠️ Инварианты агрегата
Процент всегда 0..100. Урок нельзя отметить пройденным дважды (идемпотентность). CourseFinished генерируется только когда процент достигает 100. Все эти правила живут внутри агрегата - ни handler, ни use-case не должны их дублировать.
Domain Events
Все события - иммутабельные факты в прошедшем времени:
package domain
import "time"
type LessonCompleted struct {
UserID int64
CourseSlug string
LessonSlug string
OccurredAt time.Time
}
type QuizPassed struct {
UserID int64
LessonSlug string
Score int
OccurredAt time.Time
}
type CourseFinished struct {
UserID int64
CourseSlug string
OccurredAt time.Time
}
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
use DateTimeImmutable;
// Все Domain Events - final readonly: иммутабельный факт в прошедшем времени.
final readonly class LessonCompleted
{
public function __construct(
public int $userId,
public string $courseSlug,
public string $lessonSlug,
public DateTimeImmutable $occurredAt,
) {}
}
final readonly class QuizPassed
{
public function __construct(
public int $userId,
public string $lessonSlug,
public int $score,
public DateTimeImmutable $occurredAt,
) {}
}
final readonly class CourseFinished
{
public function __construct(
public int $userId,
public string $courseSlug,
public DateTimeImmutable $occurredAt,
) {}
}
from dataclasses import dataclass
from datetime import datetime
# Все Domain Events - frozen dataclass: иммутабельный факт в прошедшем времени.
@dataclass(frozen=True, slots=True)
class LessonCompleted:
user_id: int
course_slug: str
lesson_slug: str
occurred_at: datetime
@dataclass(frozen=True, slots=True)
class QuizPassed:
user_id: int
lesson_slug: str
score: int
occurred_at: datetime
@dataclass(frozen=True, slots=True)
class CourseFinished:
user_id: int
course_slug: str
occurred_at: datetime
Domain Service: QuizEvaluator
Доменный сервис содержит логику, которая не принадлежит одной сущности. QuizEvaluator оценивает ответы пользователя: ему нужны и вопросы квиза, и ответы пользователя, поэтому методом агрегата это быть не может. Критерий выбора между методом агрегата, доменным сервисом и сценарием - в уроке Domain Service vs Application Service:
package domain
import (
"fmt"
)
// QuizEvaluator - доменный сервис оценки квизов
type QuizEvaluator struct{}
type QuizQuestion struct {
ID string
CorrectAnswers []string
}
type UserAnswer struct {
QuestionID string
Answers []string
}
func (e *QuizEvaluator) Evaluate(
questions []QuizQuestion,
answers []UserAnswer,
) (QuizScore, error) {
if len(questions) == 0 {
return 0, fmt.Errorf("quiz has no questions")
}
correct := 0
for _, q := range questions {
for _, a := range answers {
if a.QuestionID == q.ID && e.isCorrect(q.CorrectAnswers, a.Answers) {
correct++
break
}
}
}
raw := correct * 100 / len(questions)
return NewQuizScore(raw)
}
// isCorrect сравнивает множества ответов целиком: тот же размер,
// каждый ответ из эталона и без повторов. Иначе при эталоне [a, b]
// ответ [a, a] прошёл бы проверку длины и вхождения.
func (e *QuizEvaluator) isCorrect(expected, actual []string) bool {
if len(expected) != len(actual) {
return false
}
want := make(map[string]struct{}, len(expected))
for _, v := range expected {
want[v] = struct{}{}
}
seen := make(map[string]struct{}, len(actual))
for _, v := range actual {
if _, ok := want[v]; !ok {
return false
}
if _, dup := seen[v]; dup {
return false
}
seen[v] = struct{}{}
}
return true
}
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
use DomainException;
final readonly class QuizQuestion
{
/** @param string[] $correctAnswers */
public function __construct(
public string $id,
public array $correctAnswers,
) {}
}
final readonly class UserAnswer
{
/** @param string[] $answers */
public function __construct(
public string $questionId,
public array $answers,
) {}
}
// QuizEvaluator - доменный сервис оценки квизов.
// Stateless: нет полей, только методы.
final class QuizEvaluator
{
/**
* @param QuizQuestion[] $questions
* @param UserAnswer[] $answers
*/
public function evaluate(array $questions, array $answers): QuizScore
{
if ($questions === []) {
throw new DomainException('quiz has no questions');
}
$correct = 0;
foreach ($questions as $q) {
foreach ($answers as $a) {
if ($a->questionId === $q->id && $this->isCorrect($q->correctAnswers, $a->answers)) {
$correct++;
break;
}
}
}
$raw = intdiv($correct * 100, count($questions));
return QuizScore::fromInt($raw);
}
/**
* @param string[] $expected
* @param string[] $actual
*/
private function isCorrect(array $expected, array $actual): bool
{
// Сравниваем множества целиком: без array_unique ответ [a, a]
// при эталоне [a, b] прошёл бы проверку длины и вхождения.
if (count($expected) !== count($actual) || count(array_unique($actual)) !== count($actual)) {
return false;
}
$set = array_flip($expected);
foreach ($actual as $v) {
if (!isset($set[$v])) {
return false;
}
}
return true;
}
}
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class QuizQuestion:
question_id: str
correct_answers: list[str]
@dataclass(frozen=True, slots=True)
class UserAnswer:
question_id: str
answers: list[str]
class QuizEvaluator:
"""Доменный сервис оценки квизов.
Stateless: нет полей, только методы.
"""
def evaluate(self, questions: list[QuizQuestion], answers: list[UserAnswer]) -> QuizScore:
if not questions:
raise DomainError("quiz has no questions")
correct = 0
for q in questions:
for a in answers:
if a.question_id == q.question_id and self._is_correct(q.correct_answers, a.answers):
correct += 1
break
raw = correct * 100 // len(questions)
return QuizScore(raw)
def _is_correct(self, expected: list[str], actual: list[str]) -> bool:
# Сравниваем множества целиком и запрещаем повторы:
# иначе при эталоне [a, b] ответ [a, a] засчитался бы.
return (
len(actual) == len(expected)
and len(set(actual)) == len(actual)
and set(actual) == set(expected)
)
Repository Interfaces
Интерфейсы репозиториев определяются в domain-слое. Реализация - в infra:
package domain
import "context"
type ProgressRepository interface {
FindByUserAndCourse(ctx context.Context, userID int64, slug CourseSlug) (*CourseProgress, error)
Save(ctx context.Context, progress *CourseProgress) error
}
type CourseRepository interface {
FindBySlug(ctx context.Context, slug CourseSlug) (*Course, error)
ListAll(ctx context.Context) ([]Course, error)
}
<?php
declare(strict_types=1);
namespace App\Learning\Domain;
// Интерфейсы - не final, это контракты.
interface ProgressRepository
{
public function findByUserAndCourse(int $userId, CourseSlug $slug): CourseProgress;
public function save(CourseProgress $progress): void;
}
interface CourseRepository
{
public function findBySlug(CourseSlug $slug): Course;
/** @return Course[] */
public function listAll(): array;
}
from typing import Protocol
# Интерфейсы - Protocol, это контракты.
class ProgressRepository(Protocol):
def find_by_user_and_course(self, user_id: int, slug: CourseSlug) -> CourseProgress: ...
def save(self, progress: CourseProgress) -> None: ...
class CourseRepository(Protocol):
def find_by_slug(self, slug: CourseSlug) -> Course: ...
def list_all(self) -> list[Course]: ...
Скетч GORM-реализации:
package infra
import (
"context"
"fmt"
"time"
"gorm.io/gorm"
"myapp/internal/learning/domain"
)
type GORMProgressRepository struct {
db *gorm.DB
}
type progressModel struct {
ID int64 `gorm:"primaryKey"`
UserID int64 `gorm:"index:idx_user_course,unique"`
CourseSlug string `gorm:"index:idx_user_course,unique"`
Percent int
StartedAt time.Time
Lessons []lessonProgressModel `gorm:"foreignKey:ProgressID"`
}
func (progressModel) TableName() string { return "course_progress" }
type lessonProgressModel struct {
ID int64 `gorm:"primaryKey"`
ProgressID int64 `gorm:"index"`
LessonSlug string
HasQuiz bool
Completed bool
QuizScore *int
CompletedAt *time.Time
}
func (lessonProgressModel) TableName() string { return "lesson_progress" }
func (r *GORMProgressRepository) FindByUserAndCourse(
ctx context.Context, userID int64, slug domain.CourseSlug,
) (*domain.CourseProgress, error) {
var model progressModel
err := r.db.WithContext(ctx).
Preload("Lessons").
Where("user_id = ? AND course_slug = ?", userID, slug.String()).
First(&model).Error
if err != nil {
return nil, fmt.Errorf("find progress: %w", err)
}
// toDomain собирает агрегат через domain.RestoreCourseProgress:
// закрытые поля агрегата из другого пакета не заполнить.
return r.toDomain(model), nil
}
func (r *GORMProgressRepository) Save(
ctx context.Context, p *domain.CourseProgress,
) error {
model := r.toModel(p)
// FullSaveAssociations: без него GORM при Save делает для дочерних
// строк upsert без обновления полей, и изменённые Completed, QuizScore,
// CompletedAt у lesson_progress не попали бы в базу.
return r.db.WithContext(ctx).
Session(&gorm.Session{FullSaveAssociations: true}).
Save(&model).Error
}
<?php
declare(strict_types=1);
namespace App\Learning\Infrastructure\Doctrine;
use App\Learning\Domain\CourseProgress;
use App\Learning\Domain\CourseSlug;
use App\Learning\Domain\ProgressNotFoundException;
use App\Learning\Domain\ProgressRepository;
use Doctrine\ORM\EntityManagerInterface;
use DateTimeImmutable;
// Doctrine ORM entity-модели (отдельно от доменных классов).
// Маппинг через атрибуты в реальной кодовой базе.
final class ProgressModel
{
public int $id;
public int $userId;
public string $courseSlug;
public int $percent;
public DateTimeImmutable $startedAt;
/** @var LessonProgressModel[] */
public array $lessons = [];
}
final class LessonProgressModel
{
public int $id;
public int $progressId;
public string $lessonSlug;
public bool $hasQuiz;
public bool $completed;
public ?int $quizScore;
public ?DateTimeImmutable $completedAt;
}
final class DoctrineProgressRepository implements ProgressRepository
{
public function __construct(
private readonly EntityManagerInterface $em,
) {}
public function findByUserAndCourse(int $userId, CourseSlug $slug): CourseProgress
{
$model = $this->em->getRepository(ProgressModel::class)
->findOneBy(['userId' => $userId, 'courseSlug' => $slug->value()]);
if ($model === null) {
throw new ProgressNotFoundException();
}
return $this->toDomain($model);
}
public function save(CourseProgress $progress): void
{
$model = $this->toModel($progress);
$this->em->persist($model);
$this->em->flush();
}
private function toDomain(ProgressModel $m): CourseProgress { /* ... */ }
private function toModel(CourseProgress $p): ProgressModel { /* ... */ }
}
# Скетч на SQLAlchemy 2.0 (аналог GORM): ORM-модели отдельно от доменных классов.
from datetime import datetime
from sqlalchemy import ForeignKey, UniqueConstraint, select
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
Session,
mapped_column,
relationship,
selectinload,
)
from myapp.learning import domain
class Base(DeclarativeBase):
pass
class ProgressModel(Base):
__tablename__ = "course_progress"
__table_args__ = (UniqueConstraint("user_id", "course_slug", name="idx_user_course"),)
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int]
course_slug: Mapped[str]
percent: Mapped[int]
started_at: Mapped[datetime]
lessons: Mapped[list["LessonProgressModel"]] = relationship(back_populates="progress")
class LessonProgressModel(Base):
__tablename__ = "lesson_progress"
id: Mapped[int] = mapped_column(primary_key=True)
progress_id: Mapped[int] = mapped_column(ForeignKey("course_progress.id"), index=True)
lesson_slug: Mapped[str]
has_quiz: Mapped[bool]
completed: Mapped[bool]
quiz_score: Mapped[int | None]
completed_at: Mapped[datetime | None]
progress: Mapped[ProgressModel] = relationship(back_populates="lessons")
class SQLAlchemyProgressRepository:
def __init__(self, session: Session) -> None:
self._session = session
def find_by_user_and_course(self, user_id: int, slug: domain.CourseSlug) -> domain.CourseProgress:
stmt = (
select(ProgressModel)
.options(selectinload(ProgressModel.lessons))
.where(ProgressModel.user_id == user_id, ProgressModel.course_slug == str(slug))
)
model = self._session.scalars(stmt).one_or_none()
if model is None:
raise LookupError(f"find progress: user={user_id} course={slug}")
return self._to_domain(model)
def save(self, progress: domain.CourseProgress) -> None:
model = self._to_model(progress)
self._session.merge(model)
self._session.commit()
def _to_domain(self, model: ProgressModel) -> domain.CourseProgress: ...
def _to_model(self, progress: domain.CourseProgress) -> ProgressModel: ...
Application Service: CompleteLessonUseCase
Use-case оркестрирует весь поток: загрузить агрегат, выполнить операцию, сохранить, опубликовать события. Команда на входе вместо набора параметров, обработка доменных и инфраструктурных ошибок по-разному, отсутствие логирования внутри - всё это шаблон из урока Use Case: сценарии вместо «толстых сервисов»:
package app
import (
"context"
"fmt"
"myapp/internal/learning/domain"
)
type CompleteLessonCommand struct {
UserID int64
CourseSlug string
LessonSlug string
}
type CompleteLessonUseCase struct {
progressRepo domain.ProgressRepository
publisher domain.EventPublisher
}
func NewCompleteLessonUseCase(
repo domain.ProgressRepository,
pub domain.EventPublisher,
) *CompleteLessonUseCase {
return &CompleteLessonUseCase{
progressRepo: repo,
publisher: pub,
}
}
func (uc *CompleteLessonUseCase) Execute(
ctx context.Context, cmd CompleteLessonCommand,
) error {
courseSlug, err := domain.NewCourseSlug(cmd.CourseSlug)
if err != nil {
return fmt.Errorf("invalid course slug: %w", err)
}
lessonSlug, err := domain.NewLessonSlug(cmd.LessonSlug)
if err != nil {
return fmt.Errorf("invalid lesson slug: %w", err)
}
progress, err := uc.progressRepo.FindByUserAndCourse(ctx, cmd.UserID, courseSlug)
if err != nil {
return fmt.Errorf("load progress: %w", err)
}
if err := progress.CompleteLesson(lessonSlug); err != nil {
return fmt.Errorf("complete lesson: %w", err)
}
if err := uc.progressRepo.Save(ctx, progress); err != nil {
return fmt.Errorf("save progress: %w", err)
}
// Публикуем события ПОСЛЕ успешного сохранения
uc.publisher.Publish(ctx, progress.FlushEvents()...)
return nil
}
<?php
declare(strict_types=1);
namespace App\Learning\Application;
use App\Learning\Domain\CourseSlug;
use App\Learning\Domain\EventPublisher;
use App\Learning\Domain\LessonSlug;
use App\Learning\Domain\ProgressRepository;
// Command - final readonly, факт намерения.
final readonly class CompleteLessonCommand
{
public function __construct(
public int $userId,
public string $courseSlug,
public string $lessonSlug,
) {}
}
// Application Service - оркестрирует сценарий.
final class CompleteLessonUseCase
{
public function __construct(
private readonly ProgressRepository $progressRepo,
private readonly EventPublisher $publisher,
) {}
public function execute(CompleteLessonCommand $cmd): void
{
$courseSlug = CourseSlug::fromString($cmd->courseSlug);
$lessonSlug = LessonSlug::fromString($cmd->lessonSlug);
$progress = $this->progressRepo->findByUserAndCourse($cmd->userId, $courseSlug);
$progress->completeLesson($lessonSlug);
$this->progressRepo->save($progress);
// Публикуем события ПОСЛЕ успешного сохранения
$this->publisher->publish(...$progress->pullEvents());
}
}
from dataclasses import dataclass
from myapp.learning import domain
# Command - frozen dataclass, факт намерения.
@dataclass(frozen=True, slots=True)
class CompleteLessonCommand:
user_id: int
course_slug: str
lesson_slug: str
# Application Service - оркестрирует сценарий.
class CompleteLessonUseCase:
def __init__(self, repo: domain.ProgressRepository, pub: domain.EventPublisher) -> None:
self._progress_repo = repo
self._publisher = pub
def execute(self, cmd: CompleteLessonCommand) -> None:
# ValueError из конструкторов VO и DomainError из агрегата пролетают
# наверх как есть: контекст сохраняет traceback, а в HTTP-статусы
# их переводит внешний слой.
course_slug = domain.CourseSlug(cmd.course_slug)
lesson_slug = domain.LessonSlug(cmd.lesson_slug)
progress = self._progress_repo.find_by_user_and_course(cmd.user_id, course_slug)
progress.complete_lesson(lesson_slug)
self._progress_repo.save(progress)
# Публикуем события ПОСЛЕ успешного сохранения
self._publisher.publish(*progress.flush_events())
Event Handler: GrantCertificate
Обработчик реагирует на CourseFinished и выдаёт сертификат:
package handlers
import (
"context"
"log/slog"
"myapp/internal/learning/domain"
)
type GrantCertificate struct {
certRepo CertificateRepository
logger *slog.Logger
}
type CertificateRepository interface {
Issue(ctx context.Context, userID int64, courseSlug string) error
}
func NewGrantCertificate(
repo CertificateRepository, logger *slog.Logger,
) *GrantCertificate {
return &GrantCertificate{certRepo: repo, logger: logger}
}
func (h *GrantCertificate) Handle(ctx context.Context, event interface{}) {
e, ok := event.(domain.CourseFinished)
if !ok {
return
}
if err := h.certRepo.Issue(ctx, e.UserID, e.CourseSlug); err != nil {
h.logger.Error("failed to issue certificate",
slog.Int64("user_id", e.UserID),
slog.String("course", e.CourseSlug),
slog.String("err", err.Error()),
)
return
}
h.logger.Info("certificate issued",
slog.Int64("user_id", e.UserID),
slog.String("course", e.CourseSlug),
)
}
<?php
declare(strict_types=1);
namespace App\Learning\Application\Handler;
use App\Learning\Domain\CourseFinished;
use App\Learning\Infrastructure\EventHandler;
use Psr\Log\LoggerInterface;
// CertificateRepository - порт в Domain (интерфейс).
namespace App\Learning\Domain;
interface CertificateRepository
{
public function issue(int $userId, string $courseSlug): void;
}
// Event Handler - реагирует на CourseFinished.
namespace App\Learning\Application\Handler;
use App\Learning\Domain\CertificateRepository;
use App\Learning\Domain\CourseFinished;
use App\Learning\Infrastructure\EventHandler;
use Psr\Log\LoggerInterface;
use Throwable;
final class GrantCertificate implements EventHandler
{
public function __construct(
private readonly CertificateRepository $certRepo,
private readonly LoggerInterface $logger,
) {}
public function handle(object $event): void
{
if (!$event instanceof CourseFinished) {
return;
}
try {
$this->certRepo->issue($event->userId, $event->courseSlug);
} catch (Throwable $e) {
$this->logger->error('failed to issue certificate', [
'user_id' => $event->userId,
'course' => $event->courseSlug,
'err' => $e->getMessage(),
]);
return;
}
$this->logger->info('certificate issued', [
'user_id' => $event->userId,
'course' => $event->courseSlug,
]);
}
}
import logging
from typing import Protocol
from myapp.learning import domain
class CertificateRepository(Protocol):
"""Порт (интерфейс)."""
def issue(self, user_id: int, course_slug: str) -> None: ...
# Event Handler - реагирует на CourseFinished.
class GrantCertificate:
def __init__(self, repo: CertificateRepository, logger: logging.Logger) -> None:
self._cert_repo = repo
self._logger = logger
def handle(self, event: object) -> None:
if not isinstance(event, domain.CourseFinished):
return
try:
self._cert_repo.issue(event.user_id, event.course_slug)
except Exception as err:
self._logger.error(
"failed to issue certificate",
extra={"user_id": event.user_id, "course": event.course_slug, "err": str(err)},
)
return
self._logger.info(
"certificate issued",
extra={"user_id": event.user_id, "course": event.course_slug},
)
ℹ️ Ошибки в логгере
В коде выше стоит
slog.String("err", err.Error()), ноslog.Any("err", err)сработал бы так же: JSONHandler изlog/slogсам выводит ошибку черезError(). А вотjson.Marshalошибку действительно не сериализует (получится{}), поэтомуerr.Error()нужен, только если ошибку кладут в свою структуру и маршалят вручную.
Интеграция контекстов Learning и Identity
Контекст Learning не знает о внутренней модели Identity. Связь - через интерфейс и ACL-адаптер:
// В domain/ контекста Learning - только интерфейс.
// Он не знает ни про Identity, ни про способ получения данных.
package domain
import "context"
type UserInfoProvider interface {
GetEmail(ctx context.Context, userID int64) (Email, error)
}
Реализация живёт в другом пакете и в другом слое - это и есть антикоррупционный слой между контекстами:
// В infra/ - адаптер, который обращается к контексту Identity
package infra
import (
"context"
"fmt"
"myapp/internal/identity"
"myapp/internal/learning/domain"
)
type IdentityACLAdapter struct {
identitySvc identity.UserService
}
func (a *IdentityACLAdapter) GetEmail(
ctx context.Context, userID int64,
) (domain.Email, error) {
user, err := a.identitySvc.FindByID(ctx, userID)
if err != nil {
return "", fmt.Errorf("identity lookup: %w", err)
}
return domain.NewEmail(user.Email)
}
<?php
declare(strict_types=1);
// В Domain контекста Learning - только интерфейс
namespace App\Learning\Domain;
interface UserInfoProvider
{
public function getEmail(int $userId): Email;
}
// В Infrastructure - адаптер, который обращается к контексту Identity
namespace App\Learning\Infrastructure;
use App\Identity\Domain\UserService;
use App\Learning\Domain\Email;
use App\Learning\Domain\UserInfoProvider;
final class IdentityAclAdapter implements UserInfoProvider
{
public function __construct(
private readonly UserService $identitySvc,
) {}
public function getEmail(int $userId): Email
{
$user = $this->identitySvc->findById($userId);
return Email::fromString($user->email);
}
}
# В domain/ контекста Learning - только интерфейс.
# Он не знает ни про Identity, ни про способ получения данных.
from typing import Protocol
class UserInfoProvider(Protocol):
def get_email(self, user_id: int) -> Email: ...
Реализация живёт в другом пакете и в другом слое - это и есть антикоррупционный слой между контекстами:
# В infra/ - адаптер, который обращается к контексту Identity
from myapp import identity
from myapp.learning import domain
class IdentityACLAdapter:
def __init__(self, identity_svc: identity.UserService) -> None:
self._identity_svc = identity_svc
def get_email(self, user_id: int) -> domain.Email:
# Ошибка поиска в Identity пролетает наверх вместе с контекстом вызова;
# Learning получает уже свой тип Email, а не модель чужого контекста.
user = self._identity_svc.find_by_id(user_id)
return domain.Email(user.email)
Learning работает только со своим типом Email. Если Identity поменяет структуру пользователя, изменится только адаптер.
Полная картина
Как всё работает вместе при вызове "пользователь прошёл урок":
1. HTTP Handler получает POST /api/lessons/{slug}/complete
2. Handler создаёт CompleteLessonCommand и вызывает UseCase
3. UseCase загружает CourseProgress из ProgressRepository
4. CourseProgress.CompleteLesson() проверяет инварианты,
меняет состояние, собирает события
5. UseCase сохраняет агрегат через ProgressRepository
6. UseCase публикует FlushEvents() через EventPublisher
7. GrantCertificate handler проверяет CourseFinished
8. UpdateStats handler записывает аналитику
Каждый слой делает одну вещь. Домен не знает о базе данных. Use-case не знает о HTTP. Handler не содержит бизнес-логики.
Мини-задание
- Реализуй Value Object
TrackSlugпо аналогии сCourseSlug - Добавь метод
ResetLesson(slug)в агрегатCourseProgressс генерацией событияLessonReset - Напиши use-case
StartCourseUseCase, который создаёт новыйCourseProgressдля пользователя - Реализуй обработчик события
QuizPassed, который логирует результат черезslog - Добавь в словарь Ubiquitous Language два новых термина из своего проекта