Luminova Framework

PHP Luminova: HTTP Controller Class

Last updated: 2026-09-02 13:08:46

HTTP Base Controller is the starting point for building web and API controllers in Luminova. It helps you handle incoming requests, run your template logic, and send responses back to the client.

The HTTP Base Controller is the foundation for building HTTP controllers in Luminova.It supports both MVC (Model-View-Controller) and HMVC (Hierarchical MVC) structures, serving as the link between your application logic and the routing system. Its primary role is to handle incoming requests and generate the correct response back to the client.


What does the Base Controller do?

  • Handles Requests - Receives and processes incoming HTTP requests.
  • Executes Application Logic - Works with models, services, and utilities to perform operations.
  • Generates Responses - Returns templates using the view() method, raw or JSON payloads using the send() method, or raw output using the response() helper.

Key Features

When you extend Base Controller, you get built-in features that reduce repetitive code and keep your application consistent. You spend less time on setup and more time writing your app logic.

  1. Faster with Lazy Loading

    • Properties like $app, $request, and $input load only when you use them, saving memory and improving performance.
  2. Works Seamlessly with Routing

    • Automatically links to Luminova's routing system.
    • Makes it easy to handle requests, validate data, and send responses.
  3. Easy to Extend and Organize

    • Build your own controllers on top of base controller without extra setup.
    • Supports both simple MVC and more modular HMVC structures, great for small apps or large projects.
  4. Cleaner Route Definitions with PHP Attributes

Define routes directly in your controller with simple annotations:

  • Luminova\Attributes\Route - For URI routing view handling.
  • Luminova\Attributes\Error - For controller scope error handling.
  • Luminova\Attributes\Prefix - For controller scope allowed URI prefixing.
  1. Flexible Responses

Easily return different formats using

  • Luminova\Template\Response - Great for APIs, web pages, or mixed apps
  • Luminova\Template\View Great for Templates, Web pages or mixed apps
  • self::send() - Great for quickly sending a JSON, array, object, or string payload without constructing a Response object

Routable Methods Return Type

A routable method in a controller can return:

  • An integer status exit code (e.g., STATUS_SUCCESS, STATUS_ERROR)

  • A Luminova\Template\Response instance

  • Any class implementing Luminova\Interface\ContentResponseInterface

  • STATUS_SUCCESS (0)The request was handled correctly, and the response was rendered successfully.

    • Common after loading a view or completing an action.
    • In middleware, this lets the request continue to the next controller or action.
  • STATUS_ERROR (1)The request could not be handled properly.

    • The routing system responds with a 404 View Not Found error.
    • Use this when processing fails, authentication blocks access, or no valid view is found.
  • STATUS_SILENCE (2)The request was processed, but nothing was explicitly returned or displayed.

    • The router takes no further action.
    • Useful for background tasks, APIs with no visible output, or cases where an empty response is expected.
    • If nothing is rendered, the user may see a blank page.

Examples

In Luminova, creating a controller is simple: extend Luminova\Base\Controller.This gives your controller built-in framework features and ensures your methods follow the correct conventions.

Best Practices:

  • Keep your controllers thin by delegating business logic to services or models.
  • Use dependency injection where applicable.
  • Override onCreate for setup tasks specific to your controller.
  • Place your controllers in the appropriate directory based on the architecture (MVC or HMVC).
  • Use descriptive module names for better organization.

MVC Controller

A basic MVC controller example:

// /app/Controllers/Http/MainController.php

namespace App\Controllers\Http;

use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use App\Errors\Controllers\AppError;

#[Prefix(pattern: '/(:root)', onError: [AppError::class, 'onWebError'])]
class MainController extends Controller 
{
    /**
     * Called during initialization.
     */
    protected function onCreate(): void
    {
        // Optional: initialize data here
    }

    /**
     * Index page
     */
    #[Route('/', methods: ['GET'])]
    public function index(): int 
    {
        return $this->view('index');
        // Loads /resources/Views/index.php
    }

    /**
     * About page
     */
    #[Route('/about', methods: ['GET'])]
    public function about(): int 
    {
        return $this->view('about');
        // Loads /resources/Views/about.php
    }
}

HMVC Controllers

HMVC controllers are similar to MVC, but:

  • Namespaces differ
  • Modules require registration in the application class
  • Non-root module controllers must define their module name and controllers namespace
  • Each module contains it own template view directory

Root Module Example:

// /app/Modules/Controllers/Http/MainController.php

namespace App\Modules\Controllers\Http;

use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use App\Errors\Controllers\AppError;

#[Prefix(pattern: '/(:root)', onError: [AppError::class, 'onWebError'])]
class MainController extends Controller 
{
    protected function onCreate(): void
    {
        // Optional initialization
    }

    /**
     * Index page
     */
    #[Route('/', methods: ['GET'])]
    public function index(): int 
    {
        return $this->view('index');
        // Loads /app/Modules/Views/index.php
    }

    /**
     * About page
     */
    #[Route('/about', methods: ['GET'])]
    public function about(): int 
    {
        return $this->view('about');
        // Loads /app/Modules/Views/about.php
    }
}

Custom HMVC Module Example:

// /app/Modules/Post/Controllers/Http/PostController.php

namespace App\Modules\Post\Controllers\Http;

use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use App\Errors\Controllers\AppError;

#[Prefix(pattern: '/post/(:root)', onError: [AppError::class, 'onWebError'])]
class PostController extends Controller 
{
    protected function onCreate(): void
    {
        // Register the module (matches directory name)
        $this->tpl->setModule('Post');

        // Optional: other initialization
    }

    /**
     * Index list all posts
     */
    #[Route('/post', methods: ['GET'])]
    public function posts(): int 
    {
        return $this->view('posts');
        // Loads /app/Modules/Post/Views/posts.php
    }

    /**
     * About post
     */
    #[Route('/post/(:integer)', methods: ['GET'])]
    public function about(int $postId): int 
    {
        return $this->view('post');
        // Loads /app/Modules/Post/Views/post.php
    }
}

Register Custom Module Namespace

Register namespace for HMVC Post module controllers:

// /app/Application.php

namespace App;

class Application extends Luminova\Foundation\Core\Application
{
    protected function onCreate(): void 
    {
        $this->router->addNamespace('\\App\\Modules\\Post\\Controllers\\');
    }
}

View Template

Example of a simple template file for an index page:

<!-- File: resources/View/index.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Index Example</title>
</head>
<body>
    Current Theme: <?= $this->_theme; ?>
</body>
</html>

Template Handling

Rendering a View

Render a template by passing its name without the .php extension:

#[Route('/', methods: ['GET'])]
public function mainIndex(): int 
{
    return $this->view('index', [
        'theme' => 'dark'
    ], 'html', 200);
}

Using the view template instance:

#[Route('/', methods: ['GET'])]
public function mainIndex(): int 
{
    return $this->tpl->view('index', 'html')->render([
        'theme' => 'dark'
    ], 200);
}

Returning View Content

If you want the rendered content without sending it directly, use contents():

#[Route('/', methods: ['GET'])]
public function mainIndex(): int 
{
    $content = $this->contents('index', [
        'theme' => 'dark'
    ], 'html', 200);

    // You can process or log $content here
    return $content !== null ? STATUS_SUCCESS : STATUS_SILENCE;
}

Equivalent using the application instance:

#[Route('/', methods: ['GET'])]
public function mainIndex(): int 
{
    $content = $this->tpl->view('index', 'html')->contents([
        'theme' => 'dark'
    ], 200);
    // Handle contents

    return STATUS_SILENCE;
}

Useful for sending templates as emails or saving output for later.


Response Handling

Sending a Quick Response

For simple string, array, or object payloads, use send(). Non-string payloads are automatically JSON encoded:

#[Route('/foo', methods: ['GET'])]
public function foo(): int 
{
    return $this->send([
        'status' => 'ok',
        'message' => 'Account created'
    ], [], 200);
}

Returning a Response Object

You can return a Response object directly:

use Luminova\Template\Response;
use Luminova\Interface\ContentResponseInterface;

#[Route('/foo', methods: ['GET'])]
public function foo(): ContentResponseInterface 
{
   return new Response(200, content: ['data' => 'Hello World!']);

   // Alternative using helper:
   // return Luminova\Funcs\response()->content(['data' => 'Hello World!']);
}

Middleware

Return a response from middleware logic:

use Luminova\Template\Response;
use Luminova\Interface\ContentResponseInterface;

#[Route('/(:root)', methods: ['ANY'], middleware: Route::BEFORE_MIDDLEWARE)]
public function middleware(): ContentResponseInterface|int
{
    // Assuming session is initialized in "App/Application" class
    if ($this->app->session->isOnline()) {
        return STATUS_SUCCESS;
    }

    return (new Response(401, content: ['error' => 'Access Denied!']))
        ->failed();

    // Or return status error
    // return STATUS_ERROR;
}

API Response

Customize responses using Luminova\Template\Response:

#[Route('/', methods: ['GET'])]
public function mainIndex(Luminova\Template\Response $response): int 
{
    return $response->setStatus(200)
        ->header('Content-Type', 'application/json')
        ->json([
            'foo' => 'Bar'
        ]);

    // Alternative using helper:
    // return Luminova\Funcs\response(200)->json(['foo' => 'Bar']);
}

For more view response handling, see View Response Handling documentation.


Class Definition


Properties

allowDirectIncludes

Allow direct PHP include and require statements in this controller.

When enabled, the debugger skips direct include/require enforcement for this controller during development.

protected bool $allowDirectIncludes = false;

For the class-scope equivalent, see Luminova\Attributes\AllowDirectIncludes.


request

The instance of HTTP request object (lazy).

protected readonly Luminova\Http\Request<RequestInterface, LazyObjectInterface> $request;

For more information, see HTTP Request Handling documentation.


input

The instance of user-input validation class (lazy).

protected readonly Luminova\Security\