Keeping your Laravel applications DRY with single action classes

We could put this code into the action itself, but we could also use a decorator pattern.Then, using Laravel’s IoC container, we can bind the LogCreateUser class to the CreateUser class, so the former will be injected everytime we need an instance of the latter :AppServiceProvider.phpThis make it even easier to activate/deactivate the logging with a config / environment variable :AppServiceProvider.phpSummaryUsing this approach can seems a lot of classes at first..And, of course the user registration is a simple example aimed to keep the reading short and clear..Real value starts to become clear once the complexity starts growing, because you know your code is in one place, and the boundaries are clearly defined.The benefits of using single action classes :Small unitary pieces of domain logic prevents code duplication and enhance reusability..Keep things SOLID.Easy to test in isolation against a variety of scenarios.Meaningful names makes it easier to navigate inside big project’s structureEasy to decorate.Consistency across the project : prevent code to be spread over Controllers, Models, etc..And of course, this is my approach based on my experience with Laravel this last few years and the kind of projects I had to deal with..It really worked for me and I now even use it on small/medium projects.I’d be really curious to read your thought on it, especially if your approach is different.. More details

Leave a Reply