ddd structure in php

main.php
namespace App\Domain;

// Entities
class User {
    private $id;
    private $name;
    
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }

    // Getters and setters
}

// Value Objects
class Email {
    private $email;

    public function __construct(string $email) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email address');
        }
        $this->email = $email;
    }

    public function getEmail(): string {
        return $this->email;
    }
}

// Repositories
interface UserRepositoryInterface {
    public function findById(int $id): ?User;
    public function save(User $user): void;
}

class UserRepository implements UserRepositoryInterface {
    public function findById(int $id): ?User {
        // Code to fetch user from database by id
    }

    public function save(User $user): void {
        // Code to save user to the database
    }
}

// Services
class UserService {
    private $userRepository;

    public function __construct(UserRepositoryInterface $userRepository) {
        $this->userRepository = $userRepository;
    }

    public function getUserDetails(int $userId): ?array {
        $user = $this->userRepository->findById($userId);
        if ($user) {
            return ['id' => $user->getId(), 'name' => $user->getName()];
        }
        return null;
    }
}
1445 chars
64 lines

In this example, we have created a simple structure for Domain-Driven Design in PHP. We have included entities, value objects, repositories, and services as part of the Domain layer. Each component has its responsibilities and follows the DDD principles.

related categories

gistlibby LogSnag