Skip to content

Implement DTO Pattern for Posts, Comments and Users for module templates #443

Description

@armanist

Description

Introduce DTOs for type-safe data transfer between controllers and services.

Scope

  • Posts: PostDTO
  • Comments: CommentDTO
  • Users: UserDTO

Structure

Modules/Api/DTOs/
├── PostDTO.php
├── UserDTO.php
└── CommentDTO.php

DTO Example:

namespace Modules\Api\DTOs;

class PostDTO
{
    public function __construct(
        public string $userUuid,
        public string $title,
        public string $content,
        public string $image = '',
    ) {}
}

Controller (Create):

$dto = new PostDTO(
    userUuid: auth()->user()->uuid,
    title: $validated['title'],
    content: $validated['content'],
    image: $imageName
);

$post = $this->postService->addPost($dto);

Service (Create):

public function addPost(PostDTO $dto): Post
{
    $post = $this->model->create();
    $post->fillObjectProps([
        'uuid' => uuid_ordered(),
        'user_uuid' => $dto->userUuid,
        'title' => $dto->title,
        'content' => $dto->content,
        'image' => $dto->image,
        'created_at' => date('Y-m-d H:i:s'),
    ]);
    $post->save();
    return $this->getPost($post->uuid);
}

Acceptance Criteria

  • DTOs created and used in controllers/services
  • Validation still happens before DTO instantiation
  • All tests pass
  • No breaking changes to API responses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions