Single Action Controllers

February 5, 2019
1 Minute Read

background Trying to design your code to be the most effective and performant can be an interesting challenge. There is a lot to consider - design principles and standards to name two. What works for you may not work for others.

While reading the Laravel documentation for the hundredth time (exaggeration - you get the point) Single Action Controllers came up and it was added to my one day to implement "wish" list.

Having a technology role - you have to enjoy learning. There is no way around that to stay relative. After all, it is how we get better.

“The more I learn, the more I realize how much I don’t know” - Albert Einstein

What and Why?

The purpose of a single action controller is to perform a single action.

While this type of controller does not work in all use cases, nor do I recommend having a lot of single action controllers, I found a use case for application features. This keeps your application DRY with SOLID principles. Each application feature would has it's own single action controller. You still have the constructor method available and ability extend your classes.

How to use

Create a new single action controller php artisan make:controller NewFeatureController, added PHP __invoke magic method, call your controller.

// App\Http\Controllers\NewFeatureController.php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class NewFeatureController extends Controller
    public function __invoke()
        // New Feature Logic
        return true;
// web.php

Route::post('/newfeature', 'NewFeatureContoller');

Wrap Up

I'm enjoying this strategy and will continue to use it on future projects (at least until I learn a new strategy). It has simplified the process of adding new features and reducing time to develop. Who does not love that!?