DEV Community

AL EMRAN
AL EMRAN

Posted on • Updated on

Data Transfer Object (DTO) in Laravel

Data Transfer Object (DTO) in Laravel

We are highly using DTO in Doplac CRM.

What is DTO?

DTO stands for "Data Transfer Object," and it is a design pattern that can be used to abstract the transfer of data between layers in a software application.

Why DTO ?

DTO, short for Data Transfer Object, is a pattern that aims to simplify the flow of data between layers of a software application. It allows developers to abstract the data transfer process by creating a plain old object that holds the data and its structure, and this allows for better organization and maintainability of the code. DTOs can also be used for data validation, sanitation, and optimization.

Some reason why we must use DTO:

  1. Transparent definition of data: DTO can help ensure that data is properly typed, by explicitly defining the data types for each property. This allows for stronger type checking and can prevent errors that might occur when using loosely typed data. Additionally, DTOs provide a structured way of accessing data, by exposing it through object properties, rather than anonymous properties, making the code more readable and easier to understand.

  2. Mistake-Free: DTO can help prevent mistakes in a software application by providing a clear reference to the data being transferred. When accessing data from a request object or remote request response, it can be easy to make mistakes as there is no clear reference to the data being used. However, with a DTO, all data is referenced through the properties of the DTO object. This makes it easier to see and understand the data being used, and can also prevent mistakes as the IDE will prompt the developer to use the correct properties. Additionally, DTO can also provide validation and sanitation methods to further reduce the chance of errors.

  3. Clean Code: We can maintain clean code. Other developer can easily understand that which data we need to receive.

  4. Enhancing security: With PHP type hinting, we can validate data when assigning to DTO object.

  5. Improving performance: DTO can be used to optimize data transfer by only transferring the necessary data. This can improve the performance of the application, especially when dealing with large amounts of data.

  6. Testability: DTO can be used to isolate the data layer of an application, allowing it to be tested independently of the business logic. Additionally, by using DTO, the data layer can be subject to static analysis to identify potential issues or bugs before the application is run. This can improve the overall quality and reliability of the code.

Overall, DTO can improve the organization and clarity of the code, making it easier to understand and maintain.

How we Implement ?

Way: 1

use Illuminate\Http\Request;

class TestDto
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly string|null $address,
    ) {}

    public function fromRequest(Request $request): TestDto
    {
        return new self(
            $request->input('name'),
            $request->input('email'),
            $request->input('address'),
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Way: 2

use Illuminate\Http\Request;

class TestDto
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly string|null $address,
    ) {

    }

    public function fromRequest(Request $request): TestDto
    {

        $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email', 'max:200'],
        ]);

        return new self(
            $request->input('name'),
            $request->input('email'),
            $request->input('address'),
        );
    }

}
Enter fullscreen mode Exit fullscreen mode

💡Recommendation💡: Please don't use any package for DTO.

Thank you for your time to read the article.

You can Follow me on Twitter

Our Products:

Doplac CRM

Top comments (7)

Collapse
 
alnahian2003 profile image
Al Nahian

Excellent writing, Emran vai 👐🏼
Bookmarked ✅

Collapse
 
emrancu profile image
AL EMRAN

You are most welcome.
Thank you for your inspiration.

InshaAllah will try to post regularly.
You can follow me on Twitter

Collapse
 
rafaacioly profile image
Rafael Acioly • Edited

Every time I see DTO I immediately think in Java old school code.

On my project, I like to use only the entity name in a specific namespace, e.g:

namespace App\Entities\PartnerName\Product;

class Product {}
Enter fullscreen mode Exit fullscreen mode

If there's a conflict, I use alias:

use App\Entities\PartnerName\Product as PartnerNameProduct;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
emrancu profile image
AL EMRAN

May be but it is effective.
I do not like that. You should follow standard approach.

Collapse
 
rafaacioly profile image
Rafael Acioly

DTO is a not a standard is a convention, so you can use it or not, it doesn't matter.

Thread Thread
 
emrancu profile image
AL EMRAN

Yeah.

Collapse
 
verronknowles profile image
Verron Knowles

DTOs are fluff surrounding common functionality found in a language. Also a huge waste of time in terms of troubleshooting and development. Your examples are already ripe with abuse by handling data structure (models), http requests and validation when laravel already has places/homes for this stuff.

I'd argue DTOs aren't needed at all (even in Symfony) as why would you want your the context you get from the object instantiation lost. This introduces too much isolation and overhead as context should only be lost when objects leave your application. Objects are passed by reference in PHP, so more performant.