Luminova Framework

PHP Luminova: Core Application Class

Last updated: 2026-09-02 11:11:46

Learn how to configure and extend Luminova's Core Application, including application classes, lifecycle hooks, HMVC namespace registration, runtime-specific applications, and application instance access.

The Luminova Core Application is the base class that defines the structure, lifecycle, and core functionality of a Luminova application. It provides the foundation for building both simple and complex applications.

The default application class must be named Application and located in the /app/ directory. It should extend Luminova\Foundation\Core\Application.

For applications that require different configurations or behavior based on the runtime environment, you can define multiple application classes. Register and resolve them through the Service Kernel by overriding Kernel::getApplication(). This allows the appropriate application class to be selected based on the current request context, such as HTTP, CLI or URI prefix.


Extending Application Class

A custom application class extends the core application and is used to configure routing, services, and other bootstrap logic.

The most common use case is registering HMVC module namespaces, gating environment-specific requests, and initializing application-level services.


Basic Application Class

An application class extends Luminova\Foundation\Core\Application and provides lifecycle hooks for customizing application behavior.

These hooks allow you to run application-specific logic at different stages of its lifecycle, such as initializing properties, responding to route resolution, performing cleanup, or handling application termination.

// /app/Application.php

namespace App;

class Application extends Luminova\Foundation\Core\Application
{
    protected function onPreCreate(): void {}

    protected function onCreate(): void {}

    protected function onStart(array $info): void {}

    protected function onFinish(array $info): void {}

    protected function onRouteResolved(string $context): void {}

    protected function onDestroy(): void
    {
        gc_collect_cycles();
    }

    public function onShutdown(array $error): bool
    {
        return true;
    }

    protected function onTerminated(array $info): void
    {
        Logger::debug('Application was terminated.', $info);
    }
}

It is recommended to use onCreate() to initialize or update application-specific properties instead of overriding __construct(). This keeps application initialization within the framework lifecycle and avoids unnecessary constructor customization.

Use the other lifecycle hooks when you need to perform logic at a specific stage of the application lifecycle.


Environment-Specific Applications

The kernel service can resolve different application classes based on the current runtime environment or request context.

This allows you to create separate application classes for different application scopes, such as API, admin, or web applications, and customize each one according to its requirements.

// /App/Kernel.php

public function getApplication(): Application
{
    return match (true) {
        Router::isApiPrefix()        => new \App\Apps\Api(),
        Router::isUriPrefix('admin') => new \App\Apps\Admin(),
        default                      => new \App\Application(),
    };
}

This keeps application-specific logic isolated. For example, you can define and start sessions only in applications that require them, without affecting API or other stateless applications.


HMVC Namespace Registration

When using Luminova's HMVC architecture, custom module namespaces must be registered with the router so the routing system can resolve controllers within each module.

A clean approach is to register module namespaces in the onCreate() lifecycle hook. This hook runs after the core application has been fully initialized, making the router available for additional configuration.

// /app/Application.php

namespace App;

use Luminova\Foundation\Core\Application as CoreApplication;

class Application extends CoreApplication
{
    protected function onCreate(): void
    {
        // Register HMVC module namespaces
        $this->router->addNamespace('\\App\\Modules\\Blog\\Controllers\\');
        $this->router->addNamespace('\\App\\Modules\\User\\Controllers\\');

        // Additional application setup...
    }
}

Note:

The default application namespace is registered automatically. Only additional module namespaces need to be registered.

The module name should match its URI prefix. For example, a module handling https://example.com/admin/* should use Admin as its module name. This allows the router to identify the appropriate module and resolve its controllers based on the URI prefix.


Overriding the Constructor

You can override the application constructor when custom initialization is required. When doing so, always call the parent constructor to ensure the core application is properly initialized.

// /app/Application.php

namespace App;

class Application extends Luminova\Foundation\Core\Application
{
    public function __construct()
    {
        parent::__construct();
    }
}

Note:

If you add custom parameters to the constructor, Luminova may not be able to provide the required arguments when creating the application instance. For application-specific initialization, it is recommended to use the onCreate() lifecycle hook or resolve the application through Kernel::getApplication() when custom dependencies or construction logic are required.


Usage

Accessing the Application Instance

You can access the application instance directly using the application helper or the service kernel.

Using the Helper Function

When using the application helper:

  • shared: true returns the shared application instance.
  • new: true creates a new application instance and replaces the existing shared instance.
  • new: null leaves the current shared instance unchanged.
use function Luminova\Funcs\app;

$app = app(shared: true, new: null);

If Kernel::getApplication() does not provide a custom application instance, the system falls back to App\Application.

Using the Service Kernel

You can also resolve the application directly through the service kernel.

use App\Kernel;

// Shared kernel instance
$app = Kernel::create(shared: true)->getApplication();

// Shared application instance
$app = Kernel::resolve(Kernel::SERVICE_APPLICATION, shared: true);

Note:

The automatic fallback to App\Application is not supported when resolving the application directly through the service kernel. A custom application must be explicitly configured when using this approach.


Triggering Application Hooks

The trigger() method allows you to invoke supported application lifecycle hooks manually.

Supported hooks include:

  • onStart
  • onFinish
  • onDestroy
  • onShutdown
  • onTerminated
  • onRouteResolved

For example:

$app->trigger('onStart', 'name', 'Application test started');

Use this when application-specific logic needs to be triggered outside the framework's normal lifecycle flow.


Class Definition


Constants

Lifecycle state constants returned by getState().

ConstantValueDescription
IDLE0Initial state before the application has booted.
CREATED1Set once onBoot() completes and onCreate() has executed.
COMPLETED2Set inside __destruct(), immediately before onDestroy() runs.
TERMINATED3Set after the onTerminated hook is triggered via trigger().

Properties

router

Instance of the application routing system. The property is populated once during boot and cannot be reassigned afterward.

public readonly Luminova\Interface\RouterInterface $router;

For more information about Luminova Routing System documentation.


allowIncludes

Allows direct PHP include/require statements within the application class.

When enabled, the debugger skips include/require enforcement that is otherwise applied during development.

protected bool $allowIncludes = false;

Note:

This is typically toggled via the #[AllowIncludes] class-level attribute rather than being set directly.


Methods

setInstance

Set or replace the singleton instance with a new application object.

public setInstance(Luminova\Foundation\Core\Application $new): static

Parameters:

ParameterTypeDescription
$newApplicationThe new application object.

Return Value:

static - Return the updated shared application instance.

Note:

This is an instance method, not static. Call it on an existing application instance (e.g. $app->setInstance($new);); it replaces the internally tracked shared instance used by getInstance().


getInstance

Retrieve the shared application instance.

If the Application has already been created, this method will not trigger onPreCreate or onCreate creation lifecycle again, unless $rebuilt is true.

This guarantees that the core services come from the initial Application object, while additional instances simply reuse them.

public static getInstance(bool $rebuilt = false): static

Parameters:

ParameterTypeDescription
$rebuiltboolWhether to force the full application lifecycle to run again, even if already initialized (default: false).

Return Value:

static - Return a shared application instance.


getState

Get the application lifecycle state.

public static final getState(): int

Return Value:

int - Return one of the lifecycle state constants:

  • Application::IDLE
  • Application::CREATED
  • Application::COMPLETED
  • Application::TERMINATED

bind

Bind a class or interface for dependency injection (DI) in controller methods.

This allows you to map an interface or class name to a concrete implementation or a closure.When a controller method type-hints a dependency, this binding ensures the right object is injected.

protected final bind(string $abstract, Closure|string $resolver): self 

Parameters:

ParameterTypeDescription
$abstractstringThe interface or class name to bind.
$resolverClosure|stringThe concrete class or closure returning the instance.

Return Value:

self - Return instance of application class.

Note:

This method is protected; it can only be called from within an Application subclass, typically inside onPreCreate().

Examples:

Simple and advanced bindings:

// /app/Application.php

namespace App;

use App\Models\User;
use App\Interface\UserModelInterface;
use Luminova\Foundation\Core\Application as CoreApplication;

class Application extends CoreApplication
{
  protected function onPreCreate(): void 
  {
    // Bind interface to implementation
    $this->bind(UserModelInterface::class, User::class);

    // Bind with custom initialization logic.
    $this->bind(UserModelInterface::class, function () {
      return new User(...);
    });
  }
}

Controller Usage:

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

namespace App\Controllers\Http;

use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use App\Interface\UserModelInterface;

#[Prefix(pattern: '/user/(:base)')]
class UserController extends Controller
{
  #[Route('/user/id/(:numeric)', methods: ['GET'])]
  public function user(string $id, UserModelInterface $user): int 
  {
    $data = $user->find($id);

    return $this->view('profile', [
      'user' => $data
    ]);
  }
}

trigger

Trigger protected application lifecycle hooks.

This method calls the matching on* method if it is supported. Unknown hooks throw an exception.For onTerminated, the first argument is normalized with a default uri and context.

Supported Hooks:

  • onStart
  • onFinish
  • onDestroy
  • onShutdown
  • onTerminated
  • onRouteResolved
public final trigger(string $hook, mixed ...$arguments): mixed 

Parameters:

ParameterTypeDescription
$hookstringHook method name (e.g. onStart, onDestroy).
...$arguments[mixed ...$]Optional arguments passed to the hook.

Return Value:

mixed - Return the result of the triggered hook, if any.

Throws

Note:

onPreCreate and onCreate are internal boot-time hooks and are not invokable through trigger(). Calling trigger('onPreCreate', ...) or trigger('onCreate', ...) throws BadMethodCallException.


onPreCreate

Application pre create lifecycle hook.

The onPreCreate hook is triggered once, immediately after application class is initialized before routing system runs.

This allows you to override or create a custom initialization logic before routing system starts.

protected onPreCreate(): void

Note:

Throwing an exception here terminates the application.

Examples:

Using Luminova Rate Limiter:

use Luminova\Security\RateLimiter;

protected function onPreCreate(): void 
{
  $rate = new RateLimiter();
  if(!$rate->check('key')->isAllowed()){
    $rate->respond();

    Luminova::terminate(429, 'Too many request'); // Optionally terminate application.
  }
}

Terminating early on a preflight OPTIONS request:

use Luminova\Luminova;
use Luminova\Http\Request;

protected function onPreCreate(): void 
{
  if (Request::getInstance()->isMethod('OPTIONS')) {
    header('Access-Control-Max-Age: 86400');
    Luminova::terminate(204, '');
  }
}

onCreate

Application post create lifecycle hook.

The onCreate hook is triggered once, after application class is initialized and routing system initialized.

This allows you to override properties and initialize other function requires in application.

protected onCreate(): void

Note:

Throwing an exception here terminates the application.

Example:

use Luminova\Sessions\Session;
use Luminova\Components\Object\LazyObject;
use Luminova\Interface\LazyObjectInterface;

protected ?LazyObjectInterface $session = null;

protected function onCreate(): void 
{
    $this->session = new Session();
    $this->session->setStorage('storage');
    $this->session->start();
}

onStart

Application pre request handling lifecycle hook.

The onStart hook is triggered when the application routing starts handling incoming requests.

Possible Info keys:

  • context - The application context (CLI or HTTP).
  • method - The HTTP request method.
  • uri - The request URI.
  • module - The HMVC URI module (same as prefix).
  • prefix - The URI prefix.
protected onStart(array $info): void {}

Parameters:

ParameterTypeDescription
$infoarray<string,mixed>Request state information.

onRouteResolved

Application method-based routes lifecycle hook.

The onRouteResolved lifecycle hook is triggered after a method-based route context is resolved via (/routes/), based on URI prefix or CLI.

protected onRouteResolved(string $context): void

Parameters:

ParameterTypeDescription
$contextstringThe resolved prefix or context name loaded.

onFinish

Application post request handling lifecycle hook.

The onFinish lifecycle hook is triggered after a request is handled, regardless of success or failure.

Possible Info keys:

  • filename (string|null) Optional controller class file name.
  • namespace (string|null) Optional controller class namespace.
  • method (string|null) Optional controller class method name.
  • command (array|null) Optional executed command for CLI.
  • controllers (int) Number of controller files scanned for matched attributes.
  • isCache (bool) Whether cached version rendered or new content.
  • isStaticCache (bool) Whether a static cached version was served (e.g, page.html) or regular cache (e.g, page).
protected onFinish(array $info): void {}

Parameters:

ParameterTypeDescription
$infoarray<string,mixed>The handled request and controller information.

Note:

The response has already been sent or finalized by the time this hook runs and cannot be modified.


onTerminated

Application termination lifecycle hook.

The onTerminated lifecycle hook is triggered after the application terminates via trigger('onTerminated', ...).

Info array keys:

  • status (int) Termination status (HTTP or exit code)
  • message (string) Termination message
  • title (string|null) Optional title
  • uri (string|null) Optional URI, defaulted by trigger() when omitted
  • context (string) Execution context (HTTP or CLI), always set by trigger()

Use it for final cleanup, logging, or notifications.

protected onTerminated(array $info): void 

Parameters:

ParameterTypeDescription
$infoarray<string,mixed>Additional termination information.

Examples:

Terminate application.

if (!$this->instance->ofSomethingIsTrue()) {
  Luminova::terminate(500, 'Error...');
}

Handle application termination cleanup or logging.

namespace App;

use Luminova\Logger\Logger;

class Application extends Luminova\Foundation\Core\Application
{
  protected function onTerminated(array $info): void
  {
    if (PRODUCTION) {
      Logger::debug('Application was terminated.', $info);
    }
  }
}

Note:

Triggered whenever \Luminova\Luminova::terminate() is called.


onDestroy

Application destruction lifecycle hook.

The onDestroy hook is triggered once on object destruction.Override in subclasses for custom cleanup or logging.

protected onDestroy(): void

Example:

Forces collection of any existing garbage cycles.

protected function onDestroy(): void 
{
  // gc_collect_cycles();
}

onShutdown

Application error shutdown lifecycle hook.

The onShutdown hook is triggered after script shutdown caused by a fatal error or forced termination.

This hook gives the application a final chance to inspect the shutdown state.If it returns false, the framework will skip further error handling—allowingthe application to take full control (e.g., for custom logging or rendering).

public onShutdown(array $error): bool

Parameters:

ParameterTypeDescription
$errorarray<string,mixed>The last recorded error before shutdown (if any).

Return Value:

bool - Return false to take over shutdown handling, true to let the framework proceed.

Error Arguments:

array{type:int, force?:bool, message:string, file:string, line:int}

Note:

  • This hook only gets called if shutting down because of an error.
  • It does not run when Luminova::terminate() is called unless the termination results in an error that triggers shutdown.
  • Returning true lets the framework continue with its default error page or logging flow.