Evicting PDO from Identity: Sovereign Domain Entities in a Legacy Monolith
How we evicted raw PDO queries and SQL string concatenation from our Identity controller into pure DDD domain entities and clean repository ports.
The Obsession with Domain Purity
TL;DR:
We eradicated raw PDO queries, dynamic SQL string concatenation, and array-driven identity logic from erpbsg-api’s Identity HTTP layer. By establishing a framework-agnostic, invariant-enforcing User domain entity and a UserRepositoryInterface persistence port, we decoupled core identity rules from relational storage, removed brittle PDOStatement mocking on user identity lookups, and achieved 100% green builds across 420 tests without a single regression.
“We are awake fixing this so you can sleep.”
Legacy code does not rot because engineers lack skill; it rots because frameworks make convenience cheap and boundaries optional. In early-stage monolithic development, injecting a raw database handle directly into an HTTP controller feels like pragmatism. You read a request body, build a SQL string, execute $pdo->prepare(), and return JSON. It works. The feature ships.
Then your system scales.
Suddenly, password hashing rules are copy-pasted across three endpoints. User status checks diverge between login controllers and background workers. Dynamic SQL updates fail silently when unexpected null fields arrive. Worst of all, unit testing becomes a mockery of engineering: instead of validating business rules, your tests spend dozens of lines mocking the exact sequence of SQL queries executed against a PDO driver.
In commit a33c6f8 (release v1.2.0), we executed Phase 3 of our Identity Domain-Driven Design (DDD) migration inside erpbsg-api. We evicted PDO completely from UserAccountController, populated an empty domain layer with rich entities, and restored strict architectural sovereignty.
The Diagnostics Matrix
| Failure | Root Cause | Fix | Principle |
|---|---|---|---|
| SQL Leakage in HTTP Layer | UserAccountController injected PDO directly and concatenated dynamic SQL strings. | Evicted PDO; delegated all identity persistence to UserRepositoryInterface. | Inversion of Control (IoC) |
| Anemic, Hollow Domain | src/Contexts/Identity/Domain/ was completely empty; user state lived in unvalidated arrays. | Implemented pure User entity encapsulating state, invariants, and lifecycle transitions. | Rich Domain Modeling |
| Fragile PDO Mock Chaining | UserAccountServiceTest chained 5 sequential PDOStatement mocks for a single query. | Core identity isolated behind a mocked UserRepositoryInterface; remaining enrichment queries move on an incremental track. | Test Isolation & Velocity |
| Scattered Validation Rules | Email validation and display name rules were fragmented across controllers and service scripts. | Enforced constructor invariants in User (validateEmail, non-empty display name) as Single Source of Truth. | Invariant Integrity |
| Leaking Persistence Exceptions | Raw \PDOException instances escaped directly from persistence writes to the presentation layer. | Wrapped \PDOException inside MySQLUserRepository::save() into \RuntimeException at the persistence boundary. | Exception Encapsulation |
1. The Strategy: Bounded Context Sovereignty
When we audited src/Contexts/Identity/Domain/, the directory was completely empty. The folder structure proclaimed Domain-Driven Design, but the code told a different story: UserAccountController and UserAccountService had direct custody of the relational database connection.
To reverse this architectural decay, we executed a four-tier decoupling strategy governed by Red-Green-Refactor TDD:
flowchart LR
subgraph Legacy["Legacy Architecture (Tangled)"]
direction TB
LC["UserAccountController"] -->|Injects| LPDO["PDO Instance"]
LC -->|Dynamic SQL String Concatenation| LDB[("Raw MySQL Tables")]
LC -->|Validates Arrays| LArr["Associative Arrays"]
end
subgraph Sovereign["Sovereign Architecture (DDD Decoupled)"]
direction TB
SC["UserAccountController"] -->|Invokes Commands| SPort["UserRepositoryInterface\n(Domain Port)"]
SPort -->|Implemented By| SRepo["MySQLUserRepository\n(Infrastructure Adapter)"]
SRepo -->|Maps To / From| SEntity["User Entity\n(Pure Domain)"]
SRepo -->|Transactional Prepared SQL| SDB[("MySQL Database")]
end
The Four Sovereign Layers
-
The Rich Domain Entity (
src/Contexts/Identity/Domain/User.php): A framework-agnostic, ORM-free domain entity (using only standard PHP plusRamsey\Uuid\Uuidfor v4 ID generation in this release). It represents universal identity using our Display Name First SSOT (users.name), meaningusers.nameserves as the single canonical source of truth whilegiven_nameandfamily_nameremain optional, UI-derived metadata fields. It enforces strict constructor invariants:validateEmailrejects RFC-invalid emails viaFILTER_VALIDATE_EMAIL, andvalidateNamerejects empty or whitespace-only strings. It provides explicit named constructors (User::createNew()andUser::fromState()for reconstituting persistence rows),toArray(), immutable getters, and business methods (updateProfile,changePassword,verifyPassword,hasPassword,deactivate,reactivate,recordFailedLogin,resetFailedLogins,verifyEmail,isEmailVerified). -
The Persistence Port (
src/Contexts/Identity/Domain/UserRepositoryInterface.php): A strict contract residing inside the domain namespace. It knows nothing of MySQL, PDO, or SQL tables. It declares atomic retrieval and persistence contracts:save(User $user): voidfindById(string $id): ?UserfindActiveById(string $id): ?UserfindByEmail(string $email): ?UserfindByGoogleId(string $googleId): ?UserexistsByEmail(string $email, ?string $excludeUserId = null): boolfindPaginated(?string $search = null, ?bool $isActive = null, int $limit = 10, int $offset = 0): array(PHPDoc typed as@return array{data: User[], total: int})deactivate(string $id): boolreactivate(string $id): bool
-
The Infrastructure Adapter (
src/Contexts/Identity/Infrastructure/Repository/MySQLUserRepository.php): The concrete adapter implementingUserRepositoryInterface. It receives thePDOinstance and executes parameterized queries (INSERT INTO users (...) VALUES (...) ON DUPLICATE KEY UPDATE ...). Onsave(), any caught\PDOExceptionis wrapped into a\RuntimeExceptionso write-path SQL errors do not escape raw from the repository boundary. -
Dependency Injection Wiring (
config/bootstrap.php): Our DI container bindsUserRepositoryInterface::classtoMySQLUserRepository.UserAccountControllerno longer knows what a database is.
2. The Craft: Surgical Decoupling
The Controller Before: The God Controller Anti-Pattern
In the legacy implementation, UserAccountController handled routing, JSON deserialization, input validation, password verification, and dynamic SQL query building in a single monolithic method:
// BEFORE: UserAccountController injecting PDO and assembling raw SQL strings
namespace App\Contexts\Identity\Infrastructure\Controller;
use PDO;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class UserAccountController
{
private PDO $pdo;
private UserAccountService $userAccountService;
public function __construct(PDO $pdo, UserAccountService $userAccountService, ...)
{
$this->pdo = $pdo;
$this->userAccountService = $userAccountService;
}
public function updateProfile(Request $request, Response $response): Response
{
$userId = $request->getAttribute('user_id');
$data = (array) $request->getParsedBody();
if (isset($data['email']) || isset($data['google_id'])) {
$response->getBody()->write(json_encode(['error' => 'Direct update of email or google_id is not allowed.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
$allowedFields = ['name', 'given_name', 'family_name', 'phone_number'];
$updateFields = [];
$updateValues = [];
foreach ($allowedFields as $field) {
if (isset($data[$field])) {
$updateFields[] = "$field = :$field";
$updateValues[$field] = $data[$field];
}
}
if (empty($updateFields)) {
$response->getBody()->write(json_encode(['error' => 'No fields provided to update.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
// Fragile dynamic SQL assembly directly inside the HTTP controller
$updateValues['id'] = $userId;
$sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :id";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($updateValues);
$response->getBody()->write(json_encode(['message' => 'Profile updated successfully.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
public function changePassword(Request $request, Response $response): Response
{
$userId = $request->getAttribute('user_id');
$body = (array) $request->getParsedBody();
$currentPassword = $body['current_password'] ?? null;
$newPassword = $body['new_password'] ?? '';
// Direct database probing for password hash verification
$stmt = $this->pdo->prepare("SELECT password FROM users WHERE id = ? AND is_active = TRUE");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
$response->getBody()->write(json_encode(['error' => 'User not found.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
if ($user['password'] !== null && (!$currentPassword || !password_verify($currentPassword, $user['password']))) {
$response->getBody()->write(json_encode(['error' => 'Invalid current password.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
$stmt = $this->pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->execute([$hashedPassword, $userId]);
$response->getBody()->write(json_encode(['message' => 'Password updated successfully.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
}
Notice the systemic flaws:
- Every endpoint had to guard field lists manually before interpolating column names into
$sql. - Password state and bcrypt verification leaked directly into the HTTP transport layer.
- Testing this controller or its sibling services required an elaborate web of
PDOandPDOStatementmocks.
The Controller After: Pure Orchestration
With our domain model and persistence port in place, the controller drops PDO completely and coordinates strictly through UserRepositoryInterface:
// AFTER: UserAccountController depends solely on the domain repository port
namespace App\Contexts\Identity\Infrastructure\Controller;
use App\Contexts\Identity\Domain\UserRepositoryInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class UserAccountController
{
private UserAccountService $userAccountService;
private UserRepositoryInterface $userRepository;
public function __construct(
UserAccountService $userAccountService,
...,
UserRepositoryInterface $userRepository
) {
$this->userAccountService = $userAccountService;
$this->userRepository = $userRepository;
}
public function updateProfile(Request $request, Response $response): Response
{
$userId = $request->getAttribute('user_id');
$data = (array) $request->getParsedBody();
if (isset($data['email']) || isset($data['google_id'])) {
$response->getBody()->write(json_encode(['error' => 'Direct update of email or google_id is not allowed.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
$user = $this->userRepository->findById($userId);
if (!$user) {
$response->getBody()->write(json_encode(['error' => 'User not found.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
// Domain invariants validated inside the pure User entity
$user->updateProfile(
isset($data['name']) ? (string) $data['name'] : $user->getName(),
isset($data['given_name']) ? (string) $data['given_name'] : $user->getGivenName(),
isset($data['family_name']) ? (string) $data['family_name'] : $user->getFamilyName(),
isset($data['phone_number']) ? (string) $data['phone_number'] : $user->getPhoneNumber()
);
$this->userRepository->save($user);
$response->getBody()->write(json_encode(['message' => 'Profile updated successfully.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
public function changePassword(Request $request, Response $response): Response
{
$userId = $request->getAttribute('user_id');
$body = (array) $request->getParsedBody();
$currentPassword = $body['current_password'] ?? null;
$newPassword = $body['new_password'] ?? '';
$user = $this->userRepository->findActiveById($userId);
if (!$user) {
$response->getBody()->write(json_encode(['error' => 'User not found.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
if ($user->hasPassword() && (!$currentPassword || !$user->verifyPassword($currentPassword))) {
$response->getBody()->write(json_encode(['error' => 'Invalid current password.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
}
// v1.2.0 transitional boundary: strength check & password_hash() will move inside User::changePassword() in Phase 4
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
$user->changePassword($hashedPassword);
$this->userRepository->save($user);
$response->getBody()->write(json_encode(['message' => 'Password updated successfully.']));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
}
The Rich Domain Entity: Full Compilable Implementation (User.php)
Below is the complete User entity shipped in erpbsg-api (src/Contexts/Identity/Domain/User.php), enforcing constructor invariants, state serialization (fromState / toArray), and domain transitions:
<?php
namespace App\Contexts\Identity\Domain;
use DateTimeImmutable;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;
class User
{
private string $id;
private string $email;
private string $name;
private ?string $password;
private ?string $givenName;
private ?string $familyName;
private ?string $phoneNumber;
private ?string $avatarUrl;
private ?string $googleId;
private bool $isActive;
private ?DateTimeImmutable $emailVerifiedAt;
private int $failedLoginAttempts;
private ?DateTimeImmutable $lastFailedLoginAt;
private ?DateTimeImmutable $createdAt;
private ?DateTimeImmutable $updatedAt;
public function __construct(
string $id,
string $email,
string $name,
?string $password = null,
?string $givenName = null,
?string $familyName = null,
?string $phoneNumber = null,
?string $avatarUrl = null,
?string $googleId = null,
bool $isActive = true,
?DateTimeImmutable $emailVerifiedAt = null,
int $failedLoginAttempts = 0,
?DateTimeImmutable $lastFailedLoginAt = null,
?DateTimeImmutable $createdAt = null,
?DateTimeImmutable $updatedAt = null
) {
$this->validateEmail($email);
$this->validateName($name);
$this->id = $id;
$this->email = strtolower(trim($email));
$this->name = trim($name);
$this->password = $password;
$this->givenName = $givenName !== null ? trim($givenName) : null;
$this->familyName = $familyName !== null ? trim($familyName) : null;
$this->phoneNumber = $phoneNumber !== null ? trim($phoneNumber) : null;
$this->avatarUrl = $avatarUrl;
$this->googleId = $googleId;
$this->isActive = $isActive;
$this->emailVerifiedAt = $emailVerifiedAt;
$this->failedLoginAttempts = $failedLoginAttempts;
$this->lastFailedLoginAt = $lastFailedLoginAt;
$this->createdAt = $createdAt;
$this->updatedAt = $updatedAt;
}
public static function createNew(
string $email,
string $name,
?string $password = null,
?string $givenName = null,
?string $familyName = null,
?string $phoneNumber = null,
?string $avatarUrl = null,
?string $googleId = null,
?string $id = null
): self {
return new self(
$id ?? Uuid::uuid4()->toString(),
$email,
$name,
$password,
$givenName,
$familyName,
$phoneNumber,
$avatarUrl,
$googleId,
true,
null,
0,
null,
new DateTimeImmutable(),
new DateTimeImmutable()
);
}
/**
* Reconstitutes the entity from persisted database state.
*
* @param array<string, mixed> $state
*/
public static function fromState(array $state): self
{
return new self(
(string) $state['id'],
(string) $state['email'],
(string) $state['name'],
isset($state['password']) ? (string) $state['password'] : null,
isset($state['given_name']) ? (string) $state['given_name'] : null,
isset($state['family_name']) ? (string) $state['family_name'] : null,
isset($state['phone_number']) ? (string) $state['phone_number'] : null,
isset($state['avatar_url']) ? (string) $state['avatar_url'] : null,
isset($state['google_id']) ? (string) $state['google_id'] : null,
(bool) ($state['is_active'] ?? true),
isset($state['email_verified_at'])
? new DateTimeImmutable((string) $state['email_verified_at'])
: null,
(int) ($state['failed_login_attempts'] ?? 0),
isset($state['last_failed_login_at'])
? new DateTimeImmutable((string) $state['last_failed_login_at'])
: null,
isset($state['created_at'])
? new DateTimeImmutable((string) $state['created_at'])
: null,
isset($state['updated_at'])
? new DateTimeImmutable((string) $state['updated_at'])
: null
);
}
/**
* Exports domain state into an associative array for relational persistence.
*
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'id' => $this->id,
'email' => $this->email,
'name' => $this->name,
'password' => $this->password,
'given_name' => $this->givenName,
'family_name' => $this->familyName,
'phone_number' => $this->phoneNumber,
'avatar_url' => $this->avatarUrl,
'google_id' => $this->googleId,
'is_active' => $this->isActive ? 1 : 0,
'email_verified_at' => $this->emailVerifiedAt?->format('Y-m-d H:i:s'),
'failed_login_attempts' => $this->failedLoginAttempts,
'last_failed_login_at' => $this->lastFailedLoginAt?->format('Y-m-d H:i:s'),
'created_at' => $this->createdAt?->format('Y-m-d H:i:s'),
'updated_at' => $this->updatedAt?->format('Y-m-d H:i:s'),
];
}
public function updateProfile(
string $name,
?string $givenName = null,
?string $familyName = null,
?string $phoneNumber = null
): void {
$this->validateName($name);
$this->name = trim($name);
$this->givenName = $givenName !== null ? trim($givenName) : null;
$this->familyName = $familyName !== null ? trim($familyName) : null;
$this->phoneNumber = $phoneNumber !== null ? trim($phoneNumber) : null;
$this->updatedAt = new DateTimeImmutable();
}
public function changePassword(string $newPasswordHash): void
{
if (empty(trim($newPasswordHash))) {
throw new InvalidArgumentException('Password hash cannot be empty.');
}
$this->password = $newPasswordHash;
$this->updatedAt = new DateTimeImmutable();
}
public function verifyPassword(string $plainPassword): bool
{
if ($this->password === null) {
return false;
}
return password_verify($plainPassword, $this->password);
}
public function hasPassword(): bool
{
return $this->password !== null && !empty($this->password);
}
public function deactivate(): void
{
$this->isActive = false;
$this->updatedAt = new DateTimeImmutable();
}
public function reactivate(): void
{
$this->isActive = true;
$this->updatedAt = new DateTimeImmutable();
}
public function recordFailedLogin(DateTimeImmutable $at): void
{
$this->failedLoginAttempts++;
$this->lastFailedLoginAt = $at;
$this->updatedAt = new DateTimeImmutable();
}
public function resetFailedLogins(): void
{
$this->failedLoginAttempts = 0;
$this->lastFailedLoginAt = null;
$this->updatedAt = new DateTimeImmutable();
}
public function verifyEmail(DateTimeImmutable $at): void
{
$this->emailVerifiedAt = $at;
$this->updatedAt = new DateTimeImmutable();
}
public function isEmailVerified(): bool
{
return $this->emailVerifiedAt !== null;
}
private function validateEmail(string $email): void
{
if (!filter_var(trim($email), FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email format.');
}
}
private function validateName(string $name): void
{
if (empty(trim($name))) {
throw new InvalidArgumentException('Name cannot be empty.');
}
}
public function getId(): string { return $this->id; }
public function getEmail(): string { return $this->email; }
public function getName(): string { return $this->name; }
public function getPassword(): ?string { return $this->password; }
public function getGivenName(): ?string { return $this->givenName; }
public function getFamilyName(): ?string { return $this->familyName; }
public function getPhoneNumber(): ?string { return $this->phoneNumber; }
public function getAvatarUrl(): ?string { return $this->avatarUrl; }
public function getGoogleId(): ?string { return $this->googleId; }
public function isActive(): bool { return $this->isActive; }
public function getEmailVerifiedAt(): ?DateTimeImmutable { return $this->emailVerifiedAt; }
public function getFailedLoginAttempts(): int { return $this->failedLoginAttempts; }
public function getLastFailedLoginAt(): ?DateTimeImmutable { return $this->lastFailedLoginAt; }
public function getCreatedAt(): ?DateTimeImmutable { return $this->createdAt; }
public function getUpdatedAt(): ?DateTimeImmutable { return $this->updatedAt; }
}
The Infrastructure Adapter: Upsert and Exception Containment
In MySQLUserRepository, we map domain state directly into MySQL using an idempotent ON DUPLICATE KEY UPDATE upsert (excerpted for the write/read core; see repository for findByEmail, findByGoogleId, existsByEmail, and findPaginated):
// src/Contexts/Identity/Infrastructure/Repository/MySQLUserRepository.php
namespace App\Contexts\Identity\Infrastructure\Repository;
use App\Contexts\Identity\Domain\User;
use App\Contexts\Identity\Domain\UserRepositoryInterface;
use PDO;
use RuntimeException;
class MySQLUserRepository implements UserRepositoryInterface
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function save(User $user): void
{
$sql = "
INSERT INTO users (
id, email, name, password, given_name, family_name, phone_number,
avatar_url, google_id, is_active, email_verified_at,
failed_login_attempts, last_failed_login_at, created_at, updated_at
) VALUES (
:id, :email, :name, :password, :given_name, :family_name, :phone_number,
:avatar_url, :google_id, :is_active, :email_verified_at,
:failed_login_attempts, :last_failed_login_at, :created_at, :updated_at
)
ON DUPLICATE KEY UPDATE
email = VALUES(email),
name = VALUES(name),
password = VALUES(password),
given_name = VALUES(given_name),
family_name = VALUES(family_name),
phone_number = VALUES(phone_number),
avatar_url = VALUES(avatar_url),
google_id = VALUES(google_id),
is_active = VALUES(is_active),
email_verified_at = VALUES(email_verified_at),
failed_login_attempts = VALUES(failed_login_attempts),
last_failed_login_at = VALUES(last_failed_login_at),
updated_at = VALUES(updated_at)
";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($user->toArray());
} catch (\PDOException $e) {
throw new RuntimeException('Failed to persist user: ' . $e->getMessage(), (int) $e->getCode(), $e);
}
}
public function findActiveById(string $id): ?User
{
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = :id AND is_active = TRUE LIMIT 1");
$stmt->execute([':id' => $id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row ? User::fromState($row) : null;
}
}
Transitional Edges in Commit a33c6f8 (Phase 4 Hardening Backlog)
Honest engineering logs report what actually shipped, including the deliberate boundaries left for the next iteration rather than rewriting history:
- Password Hashing Symmetry: In
v1.2.0,verifyPassword()already lives insideUser, whilepassword_hash()and strength checks remain insideUserAccountController::changePassword(). Moving hashing insideUser::changePassword(string $plainPassword)completes full invariant ownership inside the entity. - True Zero-Package Domain Purity:
Userhas zero framework, HTTP, or ORM coupling, yetcreateNew()still importsRamsey\Uuid\Uuid. Swapping in PHP’s nativerandom_bytes(16)UUIDv4 generator (or injecting an ID factory) eliminates the lone Composer import fromDomain/. - MySQL 8.0.20+ Upsert Row Aliases:
VALUES(col)inON DUPLICATE KEY UPDATEtriggers deprecation warnings in modern MySQL 8.x/8.4; migrating to row aliases (INSERT INTO users ... AS new_row ON DUPLICATE KEY UPDATE email = new_row.email) removes that warning. - Uniform Exception Containment:
save()catches\PDOExceptionand rethrows\RuntimeException, whereas read queries (findActiveById,findById) do not yet wrap read-path driver exceptions. - Single State-Transition Path: Both
User::deactivate()andUserRepositoryInterface::deactivate(string $id)coexist inv1.2.0. Phase 4 removes direct repository flags so lifecycle state changes always pass through entity invariants beforesave().
3. Eliminating the Mocking Tax in Unit Tests
The most devastating consequence of injecting PDO into service and controller classes is the Mocking Tax. Look at what UserAccountServiceTest was forced to do before introducing UserRepositoryInterface:
// BEFORE: The 5-Statement Mocking Tax in UserAccountServiceTest
public function testGetUserDetailReturnsEnrichedData(): void
{
$userId = 'user-uuid';
$userData = ['id' => $userId, 'email' => 'test@example.com', 'name' => 'Test User'];
$mockStmtUser = $this->createMock(PDOStatement::class);
$mockStmtUser->method('execute')->willReturn(true);
$mockStmtUser->method('fetch')->willReturn($userData);
$mockStmtRoles = $this->createMock(PDOStatement::class);
$mockStmtStaff = $this->createMock(PDOStatement::class);
$mockStmtClient = $this->createMock(PDOStatement::class);
$mockStmtMerchants = $this->createMock(PDOStatement::class);
// Sequential prepare chaining: altering ANY query order completely breaks this test
$this->mockPdo->expects($this->exactly(5))
->method('prepare')
->willReturnOnConsecutiveCalls(
$mockStmtUser,
$mockStmtRoles,
$mockStmtStaff,
$mockStmtClient,
$mockStmtMerchants
);
$result = $this->userAccountService->getUserDetail($userId);
$this->assertEquals('Test User', $result['name']);
}
This test was not verifying user identity behavior; it was coupling test setup to the exact ordinal sequence of five SQL prepare() calls.
The Decoupled Test
By injecting UserRepositoryInterface into UserAccountService, the primary user lookup no longer touches PDOStatement mocks at all:
// AFTER: Hydrating a pure User entity via UserRepositoryInterface mock
public function testGetUserDetailReturnsEnrichedData(): void
{
$userId = 'user-uuid';
$userEmail = 'test@example.com';
$userEntity = User::createNew($userEmail, 'Test User', null, null, null, null, null, null, $userId);
$this->mockUserRepo->method('findById')->with($userId)->willReturn($userEntity);
// Remaining context tables (roles, staff, client, merchants) stay isolated while Identity transitions
$this->mockPdo->expects($this->exactly(4))
->method('prepare')
->willReturnOnConsecutiveCalls($mockStmtRoles, $mockStmtStaff, $mockStmtClient, $mockStmtMerchants);
$result = $this->userAccountService->getUserDetail($userId);
$this->assertEquals('Test User', $result['name']);
$this->assertEquals($userEmail, $result['email']);
}
While the surrounding enrichment queries (roles, staff, client, merchants) remain isolated on their own incremental migration track, core user identity is now verified against a real User domain entity rather than a raw associative array stub.
The Triumphant Return: Verified Metrics
We do not declare victory based on subjective feelings of code cleanliness; we verify architectural boundaries through cold, empirical execution metrics:
- 10 New Pure Domain Unit Tests (
UserTest.php): 51 assertions verifying email/name invariants, profile updates, password hashing/verification, and active/inactive state transitions. - 7 Integration Tests (
MySQLUserRepositoryTest.php): 39 assertions verifying insert/upsert persistence, inactive user filtering (findActiveById), email/Google ID lookup, and paginated queries. - Zero Static Analysis Errors: Strict
PHPStananalysis executed across all 14 files insrc/Contexts/Identity/with0errors. - Full Test Suite Integrity:
420total tests executed acrosserpbsg-apiwith1,723assertions (0failures,0regressions). - Commit
a33c6f8Impact (Releasev1.2.0): 10 files modified,+1,057insertions,-126deletions.PDOis completely evicted fromUserAccountController.
By replacing raw database queries with pure domain entities and persistence ports, we turned technical debt into an immutable architectural asset. To explore our full catalog of architectural manifests and engineering blueprints, explore more at kr.dammgo.com.
Additional Analysis (FAQ)
Why not use an ORM like Doctrine or Eloquent?
Because Active Record and heavy ORMs couple domain entities to persistence metadata (annotations, proxy classes, or database columns). In a sovereign architecture, the domain layer must remain framework-agnostic PHP with zero ORM, HTTP, or framework dependencies. By maintaining our own UserRepositoryInterface and lightweight repository adapter, our domain model remains decoupled, fast, and immune to framework churn—while swapping out our last UUID helper package (Ramsey\Uuid) for native random_bytes() remains an isolated one-line Phase 4 refinement.
Does this pattern add boilerplate to simple CRUD operations?
Yes, and that is a deliberate architectural feature, not a bug. In trivial CRUD apps, raw SQL in controllers feels fast. In mission-critical enterprise systems, that shortcut produces untestable code, inconsistent invariants, and high failure rates. The discipline of writing a port, an entity, and an adapter pays compounding dividends every time a business rule changes or a new testing boundary is established.
dammgo labs - Engineering as Art.