Recently I’ve been reading two books that have provided helpful ideas on how to create clean maintainable Laravel code.
1) The Clean Architecture in PHP by Kristopher Wilson
2) Architecture of complex web applications (with examples in Laravel) by Adel F
The first one by Kristopher Wilson is based on “Clean Architecture” by Robert C. Martin. The basic message is that MVC is not a good pattern for complex web applications.
The Clean Architecture provides an alternative.
In this blog post I won’t describe all the elements of the Clean Architecture (better to read the book), but rather give a summary of some things I liked about the book. The author starts out by describing what poor architecture looks like and then provides various ways how we can decouple our code. These include: using design patterns, making use of SOLID design principles, using dependency injection and defining contracts with interfaces. I actually found this part of the book the most helpful part. The third part describes what the limitations of MVC are and how to use the clean architecture. This is a step up, but thankfully in the remaining part there is a case study where the author walks through creating various clean architecture elements like entities and domain services. He then gives an example on how they integrate into the Zend Framework and how it would be simple to migrate the code to Laravel thanks to the code now being framework independent. You can find the code here: https://github.com/mrkrstphr/cleanphp-example/tree/master
For me, the framework independence part is a bit extreme, but there are a lot of concepts in the book that I try to implement in my own project. I’m still trying to find the right balance though, as I find that too much abstraction can also lead to making the code more difficult to understand.
On the whole, I find the second book I’m reading on this subject “Architecture of complex web applications” a bit more practical. It also has a chapter on Dependency Injection which explains in more detail than the first book how it’s done. When it comes to “Application layers”, it gives practical tips, for instance on how to work with http requests. The pattern explained for transferring the data between layers is using Data Transfer Objects (DTO).
I also like the tips on adding static typing which can be useful for having auto-complete in one’s IDE. Some tips like using phpDoc in one’s blade template sadly only work in PhpStorm.
One thing I missed for the second book is that I couldn’t find the code examples on Github. Although the book comes with lots of code, it can be difficult understanding how the code works as a whole.
I’m still working my way through the second book and probably I’ll reread the first book too, so you can probably expect more blog posts on this topic.
Top comments (1)
If this is a correct implementation of the Clean Architecture, then I’m the sweet prince of bel air 🙄