If you familiar with Java, maybe you already known about POJO (Plain Old Java Object). Because the term of POJO first coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie on Java programming language in 2000. POJO gives us ease in understanding the types of data structures that are in a class object.
We have the case:
- So what is the name of POJO in another programming language?
- Why we need DTO in modern PHP programming?
- How to make DTO in modern php programming?
- How to implement DTO in modern PHP programming?
Answer the case:
So what is the name of POJO in another programming language?
The convention about Plain Old Object is "Plain Old programming_language_name Object". So if you on Ruby, you can call PORO (Plain Old Ruby Object) maybe Rubyist already known about it. If on PHP it's called POPO (Plain Old PHP Object). Every language can implement Plain Old Object if they have a class, or in modern way you can call it DTO.Why DTO in modern PHP programming?
DTO can guide us about data structure, and give us clarity about what the type data on that object. You can create DTO (Data Transfer Object) inside of DTO, example guide: "toArray()", "castToClass()", "toJSON()" something like that. So you carries the data or value not in variable, but on class object based. It can gives you standardisation about how to communicate from object A to object B. And give you less function paramater, you just pass with DTO class. In modern PHP programming web application we often use MVC (Model, View, Controller) then it will have often communication each object. From controller to service, controller get data return from service, and return to view. With DTO we can make better communication each object.How to make DTO in PHP programming?
You can make DTO by define what the class?, what the property? and then you can make it. DTO should have setters and getters. First things we define the class, Food have property name, price, quantity, and total price. Then we can set the value by setter function on Food DTO. If we want transform it to JSON we can call "toJSON()" function and etc. You can develop according to what you need. Example guide:
How to implement DTO in modern PHP programming?
You can start it by creating new DTO. In above example, we can call with php syntax "new Food()".
Example 1 (Simple Controller):
In example 1 we use toArray() to communicate to Model.
Example 2 (Controller, Service and Model):
We pass class object to service
We use toArray() to communicate to Model.
On below with no DTO our function store on food service is looked not maintainable, too much parameter.
Conclusion
That is a little quick implementation DTO in modern PHP. You can use DTO for simplify your parameter function and you can get better communication each object or class. You can explore more and implement to your own development according what you need. Any question, feel free to comment on below. Happy code!!
Top comments (0)