Data Transfer Objects (DTOs) are objects that are used to transfer data between layers of your application. They are often used to decouple the application's business logic from its data storage or presentation layers. So that we our business logics are in the DTOs and can be easily managed.
For example, let's say you have a Task Eloquent model that represents a task in your database. The Task model might have a title, description, and priority attribute, among others.
However, when you display a list of tasks to the user, you only want to show the title and priority of each task. Instead of creating a separate Eloquent model to represent this data, you could create a TaskListItemDTO that only has title and priority attributes.
Assume that we have the model `Task`.
It has columns:
title
description
priority
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = ['title', 'description', 'priority']; }
Let’s implement a TaskListItemDTO:
<?php namespace App\DTOs; class TaskListItemDTO { public $title; public $priority; public function __construct(string $title, string $priority) { $this->title = $title; $this->priority = $priority; } }
Now we will use it in our controller like this:
<?php namespace App\Http\Controllers; use App\DTOs\TaskListItemDTO; use App\Task; class TaskController extends Controller { public function index() { $tasks = Task::all(); $taskListItems = $tasks->map(function ($task) { return new TaskListItemDTO($task->title, $task->priority); }); return view('tasks.index', ['taskListItems' => $taskListItems]); } }
We can display the task list items as usually in ours blade file.
<ul> @foreach ($taskListItems as $task) <li>{{ $task->title }} ({{ $task->priority }})</li> @endforeach </ul>
By using Data Transfer Objects, you can separate your business logic (represented by the Task model) from the presentation logic (represented by the TaskListItemDTO and the view used to display the tasks).
There you go guys! We can use DTOs to decouple our business logics and keep our application code cleaner then ever.
Comments (1)
1 year ago
Nice stuff! I should give it a go. Thanks for the suggestion
1 year ago
Thanks for your kind comment.