Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

DTO: Value Objects and Data (Transfer) Objects in Laravel

Historically, PHP has been a "loosely typed" language, with auto-converting between strings/integers and potential "magic" or bugs because of that. Slowly, the language itself evolved with type-hinting and return types, but also more people started to create their own object types, to define their object rules for minimizing bugs. These are called VALUE OBJECTS, and in this article, we'll cover when/how to use them.


When/Why You Need a Value Object?

A quick answer would be this: you need to define the rules for the variable behavior, so if those rules are broken, PHP would throw an exception.

General string/integer/boolean variable types are often too broad to define a real-life complex business logic of the applications.

I really recommend watching the talk by Kai Sassnowski at the recent Laracon Online, where he presented three real-life examples of creating specific classes instead of integer/float/string variables.

In summary, those examples are:

  • Parameter $seconds is not just an integer, it's a positive integer, so it's an object of class Duration that implements the validation of positive number;
  • Parameter $discount is not just a float, it's a float between 0.01 and 1, so it's an object of class Discount that implements the necessary validation;
  • Parameter $deviceID is not just a string UUID, it's a device with its unique validation rules, so it's an object of class DeviceID with the validation.

So, instead of...

The full tutorial [9 mins, 1768 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses