Comprehensive reference for Forge Kernel internals, APIs, and developer utilities.
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.
Forge Kernel includes several performance optimizations to minimize reflection overhead and improve runtime performance.
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.
Caches command class locations to avoid scanning the commands directory on every request.
storage/framework/cache/app_command_class_map.phpapp/CommandsCaches service class locations for automatic service discovery.
storage/framework/cache/class-map.phpCaches middleware class locations and their registration attributes.
storage/framework/cache/middleware-map.phpapp/Middlewares, engine/Core/Http/Middlewares, module middlewaresCaches helper file locations for automatic inclusion.
storage/framework/cache/helper-map.phpapp/helpers, module helper directoriesThe PSR-4 autoloader includes file existence caching to avoid repeated file system checks.
app, forge, modules namespaces
Methods annotated with #[Cache] are wrapped with runtime-generated proxy classes.
Modules are loaded on-demand when their classes are first requested, reducing initial bootstrap time.
App\Modules\* classes are resolvedForge Kernel provides numerous traits organized by category for common functionality.
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 |
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 |
Located in engine/Core/Cache/Traits/
| Trait | Description |
|---|---|
| CacheTrait | Cache operations and utilities |
Global helper functions available throughout the application. Defined in engine/Core/Support/helpers.php.
Get environment variable value.
$dbHost = env('DB_HOST', 'localhost');
$debug = env('APP_DEBUG', false);
Cache operations. Get with one argument, set with two or three.
// Get
$data = cache('user:123');
// Set
cache('user:123', $userData, 3600);
Get configuration value using dot notation.
$timezone = config('app.timezone', 'UTC');
Get the current request host (domain + port).
$host = request_host(); // Returns: example.com:8080
Get an item from an array or object using dot notation.
$street = data_get($user, 'address.street');
$value = data_get($array, 'nested.key', 'default');
Escape HTML entities in a string.
echo e($userInput); // Escapes HTML
Output a value without escaping.
echo raw($htmlContent); // No escaping
Get the current CSRF token.
$token = csrf_token();
Generate CSRF meta tag for HTML head.
echo csrf_meta(); // <meta name="csrf-token" content="...">
Generate JavaScript to set window.csrfToken.
echo window_csrf_token();
Generate hidden CSRF input field.
echo csrf_input(); // <input type="hidden" name="_token" value="...">
Tap utility: execute callback and return value.
$result = tap($value, function($v) {
// Do something with $v
});
Render a view component.
echo component('Button', 'class', ['label' => 'Click']);
echo component('module:Button', 'class', [], true);
Load a layout template.
layout('main');
layout('module:layout', true);
Render a section in a layout.
echo section('content');
Generate form opening tag with CSRF protection.
echo form_open('/submit', 'POST', ['class' => 'form']);
Generate form closing tag.
echo form_close(); // </form>
Dump variables and exit (debug helper).
dd($var1, $var2); // Dumps and exits
Static helper classes providing common utilities. Located in engine/Core/Helpers/.
String manipulation utilities.
toCamelCase($string) - Convert to camelCasetoPascalCase($string) - Convert to PascalCasetoSnakeCase($string) - Convert to snake_casetoKebabCase($string) - Convert to kebab-casetoTitleCase($string) - Convert to Title CaseisCamelCase($string) - Check if camelCaseisPascalCase($string) - Check if PascalCaseisSnakeCase($string) - Check if snake_caseisKebabCase($string) - Check if kebab-casetruncate($string, $length, $suffix = '...') - Truncate stringslugify($string, $character = '-') - Create URL slugtoPlural($string) - Convert to plural formURL generation utilities.
generateLinks($page, $perPage, $totalPages, $orderBy, $sortBy) - Generate pagination linksgetUrl($path = 'file/uploads') - Get upload URLbaseUrl($path = '') - Get base URLID generation utilities (UUID, NanoID, ULID).
generate($type = 'uuid', $options = []) - Generate ID'uuid' (v1/v4), 'nanoid', 'ulid'UUID::generate('uuid', ['version' => 4]);
UUID::generate('nanoid', ['size' => 21]);
UUID::generate('ulid');
Password hashing utilities.
make($password) - Hash passwordcheck($password, $hash) - Verify password| 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 |
The Container class provides dependency injection and service management.
Located in engine/Core/DI/Container.php.
The container is a singleton, accessed via Container::getInstance().
$container = Container::getInstance();
Register a service class with #[Service] attribute.
$container->register(MyService::class);
Bind an interface or abstract class to a concrete implementation.
$container->bind(LoggerInterface::class, FileLogger::class, true);
Register a singleton binding.
$container->singleton(CacheManager::class, CacheManager::class);
Resolve a service instance. Uses reflection for constructor injection.
$service = $container->make(MyService::class);
Get a service by ID (alias for make).
$service = $container->get(MyService::class);
Tag services for grouped retrieval.
$container->tag('middleware', [
AuthMiddleware::class,
CsrfMiddleware::class,
]);
$middlewares = $container->tagged('middleware');
Manually set or override service instances.
$container->setInstance(MyService::class, $customInstance);
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);
Services with methods annotated with #[Cache] are automatically wrapped with cache proxy classes for performance.
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 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 |
The Autoloader class implements PSR-4 autoloading with performance optimizations.
Located in engine/Core/Autoloader.php.
Implements the PSR-4 autoloading standard for automatic class loading.
Maps namespaces to base directories:
app → BASE_PATH/appforge → BASE_PATH/enginemodules → BASE_PATH/modulesCaches file existence checks to avoid repeated file system operations:
Register additional namespace paths programmatically.
Autoloader::addPath('MyNamespace', '/path/to/classes');
The bootstrap process initializes the kernel. Setup classes are located in engine/Core/Bootstrap/.
Main bootstrap orchestrator that coordinates all setup classes.
Discovers and registers application commands. Builds command class map cache.
Initializes the dependency injection container for CLI context.
Initializes the dependency injection container for web context.
Discovers and includes helper files. Builds helper map cache.
Loads and initializes modules from the modules directory.
Initializes the routing system and loads route definitions.
Discovers services with #[Service] attribute and registers them. Builds service class map cache.
The cache system provides method-level caching with automatic proxy generation.
Multiple cache drivers are available:
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');
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);
}
}
The CacheInterceptor intercepts method calls and handles cache lookup/storage.
The ProxyGenerator creates runtime proxy classes for services with cached methods.
ProxyMarkerInterface