What is Data Transfer Object? Why do we use DTO in Laravel?

What is Data Transfer Object? Why do we use DTO in Laravel?

Posted on:February 22, 2023 at 10:00 AM

The very first question comes in my mind is that, what exactly Data Transfer Object?

DTO stands for Data Transfer Object. It is a design pattern used in software development to transfer data between different layers of an application. DTOs are typically used to encapsulate data and transport it across different parts of the system. They are commonly used in service-oriented architectures, where services communicate with each other by passing data through DTOs. The use of DTOs helps to simplify the communication between different components of an application and improves its overall maintainability.

Table of Content

How to use DTO in laravel?

I am trying to visualize DTO in laravel with a real life example.

Suppose you have a Post model with the following properties:

class Post extends Model
{
    protected $fillable = [
        'title',
        'body',
        'published_at'
    ];
}

You want to create a new Post using the data submitted in a form. However, you don’t want to pass the entire Request object to your Controller, because it may contain additional data that you don’t need. Instead, you want to create a DTO that contains only the necessary data, and pass it to your Controller.

1. Create a DTO:

I am creating a plain PHP class in the App\Http\DTO directory.

namespace App\Http\DTO;

class CreatePostDTO
{
    public string $title;
    public string $body;
    public ?DateTime $published_at;

    public function __construct(string $title, string $body, ?DateTime $published_at = null)
    {
        $this->title = $title;
        $this->body = $body;
        $this->published_at = $published_at;
    }
}

2. Use the DTO in your Controller:

Now in the PostController, I am using DTO instead of sending all the data from request.

namespace App\Http\Controllers;

use App\Http\DTO\CreatePostDTO;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    // Some other methods

    public function store(Request $request)
    {
        $postDto = new CreatePostDTO($request);

        $post = Post::create([
            'title' => $postDto->title,
            'body' => $postDto->body,
            'published_at' => $postDto->published_at,
        ]);

        return redirect()->route('posts.show', ['post' => $post]);
    }
}

In this example, we’re creating a new CreatePostDTO from the request data using constructor. We then create a new Post object and set its properties from the DTO. Finally, we save the Post object to the database. This approach allows you to easily transfer data between the Controller and Model layers of your application, while optimizing for performance and maintainability.

Why do we use DTO?

We use DTOs (Data Transfer Objects) for several reasons in software development:

  • Easy Type-hint: When you use a DTO to transfer data between layers of your application, you can take advantage of PHP’s strong type system to ensure that the data being passed around is of the correct type. This can help catch errors early in the development process and improve the overall quality of your code.

  • Encapsulation: DTOs encapsulate data and protect it from unwanted modification or access. It allows for easy management and maintenance of data.

  • Data Transformation: DTOs can be used to transform data from one format to another format. This can be useful when communicating data between different layers of an application or when communicating data between different applications.

  • Separation of Concerns: DTOs help to separate the concerns of data storage from data presentation. This makes it easier to modify the data layer or the presentation layer of an application without affecting the other layer.

  • Improved Code Readability: DTOs can help improve code readability by providing a clear and concise representation of the data being transferred between layers. This can make it easier for developers to understand and work with the code.

  • Easier Testing: By using a DTO, you’re creating a clear separation between the layers of your application, which makes it easier to test each layer in isolation. This can improve the overall quality of your code and reduce the likelihood of introducing bugs into the system.

Conclusion:

In this article, I’ll demonstrate how to use DTOs in Laravel to improve the structure and organization of your codebase. By implementing DTOs, we can simplify data transfer between different layers of our application and create a more maintainable codebase.