Source: blog.mollie.com

Writing better Controllers

Category: PHP, PHP, api, api

Controllers are a very important part of our software. In this post we’ll look at how writing controllers differently will lead our code to be more flexible, readable and easy to change. To better understand how a controller works differently in web apps, we will look at the well-known MVC model: Let’s take a closer look.

In other words, in request/response application we have something like this: As we can see, there is no back and forth between view and controller, if the controller supplies the view with everything it needs then the view should never get information from elsewhere.

Instead, if we create service classes to handle specific logic like this, then we can inject these services into our controllers, like the example bellow: In this example we extracted the user loading and the access control to different services, so we can easily inject the Redis client into the UserLoader and that is the only place we have to change, it will be very easy to test and all the other places this logic is used will just work the same.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners