API Reference

Comprehensive reference for Forge Kernel internals, APIs, and developer utilities.

Overview

This API reference provides detailed documentation for Forge Kernel internals, including performance optimizations, traits, helper functions, services, and architectural components. This documentation is intended for developers who need to understand or extend the kernel.

Note: Some APIs marked as internal may change between versions. Stable APIs are clearly indicated.

Performance Optimizations

Forge Kernel includes several performance optimizations to minimize reflection overhead and improve runtime performance.

Class Maps

Class maps cache the location of classes to avoid repeated file system scans and reflection operations. Maps are generated during development and cached in production.

AppCommandSetup

Caches command class locations to avoid scanning the commands directory on every request.

  • Cache File: storage/framework/cache/app_command_class_map.php
  • Scans: app/Commands
  • Rebuilds: Automatically on file changes in development

ServiceDiscoverSetup

Caches service class locations for automatic service discovery.

  • Cache File: storage/framework/cache/class-map.php
  • Scans: Repositories, Middlewares, Services, Events directories
  • Production: Uses cached map, skips scanning

MiddlewareLoader

Caches middleware class locations and their registration attributes.

  • Cache File: storage/framework/cache/middleware-map.php
  • Scans: app/Middlewares, engine/Core/Http/Middlewares, module middlewares

HelperDiscoverSetup

Caches helper file locations for automatic inclusion.

  • Cache File: storage/framework/cache/helper-map.php
  • Scans: app/helpers, module helper directories

Autoloader Optimizations

The PSR-4 autoloader includes file existence caching to avoid repeated file system checks.

  • Web (APCu): Uses APCu for file existence caching with 1-hour TTL
  • CLI (Memory): Uses in-memory array cache (max 8,000 entries)
  • Namespace Mapping: Maps app, forge, modules namespaces

Cache Proxy Generation

Methods annotated with #[Cache] are wrapped with runtime-generated proxy classes.

  • Proxy Classes: Generated once per class, cached in temp directory
  • Performance: Avoids reflection on every method call
  • Reuse: Proxies are reused across requests

Lazy Module Loading

Modules are loaded on-demand when their classes are first requested, reducing initial bootstrap time.

  • Trigger: Container automatically loads modules when App\Modules\* classes are resolved
  • Benefit: Only loaded modules consume memory and processing time

Traits

Forge Kernel provides numerous traits organized by category for common functionality.

Core Traits

Located in engine/Traits/

Trait Description
AuthorizeRequests Authorization helpers for request validation
CacheLifecycleHooks Cache lifecycle integration hooks
ControllerHelper Controller utilities: jsonResponse, view, apiResponse, apiError, csvResponse
DataFormatter Debug data formatting utilities
DTOHelper Data Transfer Object utilities
EnumHelper Enum manipulation utilities
FileHelper File operation helpers
HasEnvironmentVariables Environment variable access
HasMetaData Metadata support for models
HasMetadataToJson Metadata JSON serialization
HasTimestamps Automatic timestamp management
InjectsAssets Asset injection: registerAsset, injectAssets
Metadata Metadata operations
ModuleHelper Module utilities
NamespaceHelper Namespace manipulation
PaginationHelper Pagination utilities
PathHelper Path manipulation: stripBasePath
RepositoryTrait Repository pattern support
ResponseHelper Response creation: createErrorResponse, createResponse
SecurityHelper Security utilities
SoftDeletes Soft delete functionality
StringHelper String manipulation utilities
TimeTrait Time utilities

CLI Traits

Located in engine/CLI/Traits/

Trait Description
CliGenerator CLI generation utilities
CommandOptionTrait Command option handling
ManagesAssetLinks Asset link management
ManagesMaintenanceMode Maintenance mode management
OutputHelper CLI output formatting (info, error, success, warning)
Wizard Interactive CLI wizards

Cache Traits

Located in engine/Core/Cache/Traits/

Trait Description
CacheTrait Cache operations and utilities

Helper Functions

Global helper functions available throughout the application. Defined in engine/Core/Support/helpers.php.

env($key, $default = null)

Get environment variable value.

$dbHost = env('DB_HOST', 'localhost');
$debug = env('APP_DEBUG', false);

cache($key, $value = null, $ttl = null)

Cache operations. Get with one argument, set with two or three.

// Get
$data = cache('user:123');

// Set
cache('user:123', $userData, 3600);

config($key, $default = null)

Get configuration value using dot notation.

$timezone = config('app.timezone', 'UTC');

request_host()

Get the current request host (domain + port).

$host = request_host(); // Returns: example.com:8080

data_get($target, $key, $default = null)

Get an item from an array or object using dot notation.

$street = data_get($user, 'address.street');
$value = data_get($array, 'nested.key', 'default');

e($value)

Escape HTML entities in a string.

echo e($userInput); // Escapes HTML

raw($value)

Output a value without escaping.

echo raw($htmlContent); // No escaping

csrf_token()

Get the current CSRF token.

$token = csrf_token();

csrf_meta()

Generate CSRF meta tag for HTML head.

echo csrf_meta(); // <meta name="csrf-token" content="...">

window_csrf_token()

Generate JavaScript to set window.csrfToken.

echo window_csrf_token();

csrf_input()

Generate hidden CSRF input field.

echo csrf_input(); // <input type="hidden" name="_token" value="...">

tap($value, $callback)

Tap utility: execute callback and return value.

$result = tap($value, function($v) {
    // Do something with $v
});

component($name, $type = 'class', $props = [], $fromModule = false)

Render a view component.

echo component('Button', 'class', ['label' => 'Click']);
echo component('module:Button', 'class', [], true);

layout($name, $fromModule = false)

Load a layout template.

layout('main');
layout('module:layout', true);

section($name)

Render a section in a layout.

echo section('content');

form_open($action, $method = 'POST', $attrs = [])

Generate form opening tag with CSRF protection.

echo form_open('/submit', 'POST', ['class' => 'form']);

form_close()

Generate form closing tag.

echo form_close(); // </form>

dd(...$vars)

Dump variables and exit (debug helper).

dd($var1, $var2); // Dumps and exits

Helper Classes

Static helper classes providing common utilities. Located in engine/Core/Helpers/.

Strings

String manipulation utilities.

  • toCamelCase($string) - Convert to camelCase
  • toPascalCase($string) - Convert to PascalCase
  • toSnakeCase($string) - Convert to snake_case
  • toKebabCase($string) - Convert to kebab-case
  • toTitleCase($string) - Convert to Title Case
  • isCamelCase($string) - Check if camelCase
  • isPascalCase($string) - Check if PascalCase
  • isSnakeCase($string) - Check if snake_case
  • isKebabCase($string) - Check if kebab-case
  • truncate($string, $length, $suffix = '...') - Truncate string
  • slugify($string, $character = '-') - Create URL slug
  • toPlural($string) - Convert to plural form

Url

URL generation utilities.

  • generateLinks($page, $perPage, $totalPages, $orderBy, $sortBy) - Generate pagination links
  • getUrl($path = 'file/uploads') - Get upload URL
  • baseUrl($path = '') - Get base URL

UUID

ID generation utilities (UUID, NanoID, ULID).

  • generate($type = 'uuid', $options = []) - Generate ID
  • Types: 'uuid' (v1/v4), 'nanoid', 'ulid'
UUID::generate('uuid', ['version' => 4]);
UUID::generate('nanoid', ['size' => 21]);
UUID::generate('ulid');

Hash

Password hashing utilities.

  • make($password) - Hash password
  • check($password, $hash) - Verify password

Other Helper Classes

Class Description
Debuger Debug utilities: dumpAndExit
File File operations
FileHelper File helper methods
Flash Flash message handling
Format Data formatting
Framework Framework utilities
ModuleResources Module resource management
Redirect Redirect utilities
TimeConverter Time conversion utilities

Dependency Injection Container

The Container class provides dependency injection and service management. Located in engine/Core/DI/Container.php.

Singleton Pattern

The container is a singleton, accessed via Container::getInstance().

$container = Container::getInstance();

Service Registration

register($class)

Register a service class with #[Service] attribute.

$container->register(MyService::class);

bind($id, $concrete, $singleton = false)

Bind an interface or abstract class to a concrete implementation.

$container->bind(LoggerInterface::class, FileLogger::class, true);

singleton($abstract, $concrete)

Register a singleton binding.

$container->singleton(CacheManager::class, CacheManager::class);

Service Resolution

make($abstract)

Resolve a service instance. Uses reflection for constructor injection.

$service = $container->make(MyService::class);

get($id)

Get a service by ID (alias for make).

$service = $container->get(MyService::class);

Service Tags

Tag services for grouped retrieval.

$container->tag('middleware', [
    AuthMiddleware::class,
    CsrfMiddleware::class,
]);

$middlewares = $container->tagged('middleware');

Instance Management

Manually set or override service instances.

$container->setInstance(MyService::class, $customInstance);

Automatic Module Loading

When resolving App\Modules\* classes, the container automatically loads the corresponding module if not already loaded.

// Module is automatically loaded when this class is resolved
$service = $container->make(\App\Modules\ForgeAuth\Services\AuthService::class);

Cache Proxy Wrapping

Services with methods annotated with #[Cache] are automatically wrapped with cache proxy classes for performance.

Contracts & Interfaces

Interfaces and contracts available in the kernel. Located in engine/Core/Contracts/.

Interface Description
DatabaseConfigInterface Database configuration contract
DatabaseConnectionInterface Database connection contract (exec, query, prepare, transactions)
QueryBuilderInterface Query builder contract (select, where, orderBy, etc.)
DebugBarInterface Debug bar integration contract

Core Services

Core services available in the kernel. Located in engine/Core/Services/.

Service Description
ArchiveService Archive operations (zip, tar, etc.)
CacheRefreshListener Cache refresh event handling
DatabaseManager Database connection and management
GitService Git repository operations
InteractiveSelect Interactive CLI selection menus
ManifestService Module manifest management
ModuleAssetManager Module asset linking and management
RegistryService Module registry operations
TemplateGenerator Code template generation
TokenManager CSRF token generation and management
VersionService Version management and comparison

Autoloader

The Autoloader class implements PSR-4 autoloading with performance optimizations. Located in engine/Core/Autoloader.php.

PSR-4 Autoloading

Implements the PSR-4 autoloading standard for automatic class loading.

Namespace Mapping

Maps namespaces to base directories:

  • appBASE_PATH/app
  • forgeBASE_PATH/engine
  • modulesBASE_PATH/modules

File Existence Caching

Caches file existence checks to avoid repeated file system operations:

  • Web (APCu): Uses APCu for file existence caching with 1-hour TTL
  • CLI (Memory): Uses in-memory array cache with maximum 8,000 entries
  • Performance: Significantly reduces file system I/O

Path Registration

Register additional namespace paths programmatically.

Autoloader::addPath('MyNamespace', '/path/to/classes');

Bootstrap Process

The bootstrap process initializes the kernel. Setup classes are located in engine/Core/Bootstrap/.

Bootstrap

Main bootstrap orchestrator that coordinates all setup classes.

Setup Classes

AppCommandSetup

Discovers and registers application commands. Builds command class map cache.

ContainerCLISetup

Initializes the dependency injection container for CLI context.

ContainerWebSetup

Initializes the dependency injection container for web context.

HelperDiscoverSetup

Discovers and includes helper files. Builds helper map cache.

ModuleSetup

Loads and initializes modules from the modules directory.

RouterSetup

Initializes the routing system and loads route definitions.

ServiceDiscoverSetup

Discovers services with #[Service] attribute and registers them. Builds service class map cache.

Cache System

The cache system provides method-level caching with automatic proxy generation.

Cache Drivers

Multiple cache drivers are available:

  • File: File-based caching (default)
  • Memory: In-memory caching for single request
  • SQLite: SQLite database caching

Cache Manager

The CacheManager provides cache operations with tag support.

$cache = Container::getInstance()->make(CacheManager::class);
$cache->set('key', $value, 3600);
$value = $cache->get('key');

// Tagged cache
$cache->tags(['users', 'profile'])->set('user:123', $user);
$cache->clearTag('users');

Cache Attributes

Methods can be annotated with #[Cache] for automatic caching.

use Forge\Core\Cache\Attributes\Cache;

class UserService
{
    #[Cache(ttl: 3600)]
    public function getUser(int $id): User
    {
        // Expensive operation
        return $this->repository->find($id);
    }
}

Cache Interceptor

The CacheInterceptor intercepts method calls and handles cache lookup/storage.

Proxy Generation

The ProxyGenerator creates runtime proxy classes for services with cached methods.

  • Proxies are generated once per class and cached in the temp directory
  • Proxies extend the original class and implement ProxyMarkerInterface
  • Method calls are intercepted and routed through the cache interceptor
  • Avoids reflection overhead on every method call