Controllers

Instead of defining all request handling logic as callback functions in routes, you might prefer to organize this behavior using 'controller' classes. Controllers can group the logic for handling related requests into a single class.

Writing Controllers

Basic Controllers

To quickly generate a new controller, you can run the make:controller command. By default, all controllers generated by this command are stored in the http/controllers directory:

php line make:controller UserController

A controller can have any number of public methods that will respond to incoming HTTP requests:

namespace App\Http\Controllers;

use App\Models\User;

class UserController
{
    /**
     * Show the profile of a specific user.
     */
    public static function show($req, $res)
    {
        $id = $req->param('id');
        
        return $res->view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

After writing a controller class and its method, you can define a route for the controller method as follows:

use App\Http\Controllers\UserController;
 
$app->get('/user/:id', [UserController::class, 'show']);

When an incoming request matches the specified route URI, the show method of the App\Http\Controllers\UserController class will be invoked, and the route parameters will be passed to the method.

Middleware in Controllers

Middlewares can also be defined directly in controllers to apply pre-processing or post-processing logic to all routes or to a specific group of routes. This allows you to centralize the middleware logic directly within the controller structure.

namespace App\Http\Controllers;

class UserController
{
    // ... Other methods

    /**
     * Middleware to check authentication.
     */
    public static function loggedIn($req, $res, $next)
    {
        $authenticated = false; // Your authentication logic

        if (!$authenticated) {
            $res->redirect('/login');
        }

        $next();
    }
}

In this example, the loggedIn method acts as middleware to check authentication before any route is executed. This ensures that only authenticated users can access routes that use this middleware.

After writing your middleware, you can apply it to a route as follows:

use App\Http\Controllers\UserController;

$loggedIn = [UserController::class, 'loggedIn'];
 
$app->get('/user/:id', $loggedIn, [UserController::class, 'show']);

This ensures that the loggedIn middleware is executed before the show method is called for any request on the /user/:id route.


Controllers in Lithe provide an organized and efficient way to manage HTTP request handling. By centralizing the logic related to your resources, you gain code reusability and simplify the maintenance of your application.