Doctrine is one of the most famous open source ORMs for PHP. It’s based on data mapper architecture, so the core is all separated from entities. There is an Entity Manager that is in charge of doing CRUD .
Suppose that we’ve got an entity for books:
And another for chapters:
And there is a html form for adding a new book with this input for title:
<input type="text" name="title" />
So we receive form data as an array in BookController and new Book is supposed to be added like this:
Everything is neat and simple till we’ve got a few fields on book, but what if there are dozens of field? then we got to call all of the setter methods statically, also controllers are not supposed to do the logic, they receive data and pass it to other layers to do the rest of work.
Doctrine lacks of a layer that we name it Service Layer here. Service Layer is in charge of doing create and update logic by receiving array of data and calling entities setter methods dynamically based on array of data keys, so we ought to name html inputs after entities setter methods. We can also include a method for remove that receives and id and handles the rest.
So the layer’s contract will be like this
Then we implement the methods
So now let’s implement ChapterController store method, suppose that these are chapter inputs
<input type="text" name="description" />
<option value="1">Book 1</option>
<option value="2">Book 2</option>
<option value="3">Book 3</option>
So the controller is going to be like this
It’s just an idea for having better and cleaner code, there might be some problems that should be solved or even better ideas to be implemented.