Kernel API Reference

The Forge Kernel ships a small set of primitives you can call directly from your app. Distributed with version 7.0.17.

Capability APIs live with their capabilities. Routing, ForgeRouter; views and templates, ForgeView; databases and the query builder, ForgeDatabaseSQL. This page documents only what ships in the kernel itself.

Note: APIs marked with an Internal badge are used by the kernel's own machinery and may change between versions. The rest are stable.

Overview

The kernel is a small set of primitives your app builds on: a PSR-4 autoloader, a dependency injection container, a caching layer, helper functions, traits, and the bootstrap that wires everything together. Most capabilities you add — routing, views, databases — wrap these primitives rather than replace them.

Start here: this page is the reference. For how the pieces fit together and how you build on them, read Kernel Overview and Getting Started.

Performance Optimizations

The kernel minimizes repeated file-system and reflection work by building a few caches on disk. All of them live under storage/framework/cache/ and are rebuilt automatically when their source changes.

Autoloader class map

The PSR-4 autoloader records resolved classes to avoid repeated file-existence checks across requests. The map is kept in memory and persisted to storage/framework/cache/class_file_map.php. The persistent map is capped at 8,000 entries to keep memory bounded.

Compiled hooks

Module lifecycle hooks are discovered once and compiled to storage/framework/cache/compiled_hooks.php, so the kernel does not re-scan every module on each request.

Module registrations

The list of installed and enabled modules is cached to storage/framework/cache/module_registrations.php, avoiding repeated module discovery.

Cache proxy generation

Methods annotated with #[Cache] are wrapped in runtime-generated proxy classes so the kernel avoids reflection on every call. See the Cache System section below.

Command flush:cache clears these caches; the kernel rebuilds them on the next request.

Traits

The kernel ships a set of reusable traits in kernel/Traits/ (namespace Forge\Traits). Pull them into your classes with the use keyword.

Trait Purpose
CacheLifecycleHooks Trigger cache rebuilds on module lifecycle events
DTOHelper Data-transfer-object helpers
DataFormatter Normalize and format data
EnumHelper Enum utilities (values, labels, cases)
FileHelper File system helpers
HasEnvironmentVariables Bind an object to the environment
HasMetadataToJson Serialize metadata to JSON
InjectsAssets Inject assets into responses
Metadata Attach metadata to classes or objects
ModuleHelper Module-related helpers
NamespaceHelper Namespace helpers for autoloading
PathHelper Path normalization and resolution
SecurityHelper Security utilities
SoftDeletes Soft-delete behavior for data models
StringHelper String helpers (case, slug, truncate)
TimeTrait Time helpers (now, format)
ValidatorHelper Validation helpers

CLI traits

A separate set of traits lives in kernel/CLI/Traits/ (namespace Forge\CLI\Traits) for building console commands:

  • CliGenerator — generate command scaffolding
  • CommandOptionTrait — parse command options and arguments
  • ManagesAssetLinks — link module assets
  • OutputHelper — styled console output
  • Wizard — interactive question prompts

Helper Functions

The kernel exposes a small set of global helper functions defined in kernel/Core/Support/helpers.php. You do not need to import them; they are available anywhere in your app.

Function Purpose
env($key, $default = null) Read a value from the environment
config($key, $default = null) Read a configuration value
cache($key, $value = null, $ttl = null) Read a cache key; write it when a value is given
request_host() The current request host
data_get($target, $key, $default = null) Retrieve a value from an array or object using dot notation
e($value) HTML-escape a value
raw($value) Mark a value as safe, skipping escaping
tap($value, $callback) Call a callback on a value and return the value
dd($value) Dump a value and halt execution

Dependency Injection Container

The Container class (in kernel/Core/DI/Container.php) resolves and manages the services your app depends on. It is a singleton, so you reach it from anywhere.

$container = Container::getInstance();

Registering services

register($class)

Register a class marked with the #[Injectable] attribute.

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

bind($abstract, $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 shared (singleton) binding.

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

Resolving services

make($abstract)

Resolve an instance, using reflection for constructor injection.

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

get($id)

Resolve a service by id; get is a synonym for make.

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

Service tags

Group services for retrieval together.

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

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

Overriding instances

Replace a resolved service with a concrete instance manually.

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

Other container methods

  • has($abstract) — check whether a binding exists
  • getAll($ids) — resolve several services at once
  • getServiceIds() — list registered service ids
  • getServices() — list registered service instances
  • setParameter($id, $value) / getParameter($id) — store and read container parameters

The Injectable attribute

Classes you want the container to manage are marked with the single #[Injectable] attribute.

use Forge\Core\DI\Attributes\Injectable;

#[Injectable]
class MyService
{
    public function __construct(
        private CacheManager $cache,
    ) {}
}

Services with #[Cache] methods are wrapped in cache proxies automatically; see the Cache System section.

Contracts & Interfaces

Contracts live in kernel/Core/Contracts/. They define the boundaries capabilities and your own code implement.

Interface Purpose
BootstrapHookInterface Implement to run code during kernel bootstrap
ContainerServiceProviderInterface Register services with the container
EventDispatcherInterface Dispatch and listen for events
LoggerInterface Logging contract
NotificationInterface Send notifications
ViewInterface Rendering views (implemented by ForgeView)
CacheWarmerInterface Warm caches on deploy
DatabaseConfigInterface Database configuration contract
DatabaseConnectionInterface Database connection (exec, query, prepare, transactions)
QueryBuilderInterface Query builder (select, where, orderBy)
CentralQueryBuilderInterface Central query builder contract

The database contracts are implemented by ForgeDatabaseSQL; the view contract by ForgeView.

Core Services

A small set of services ships in the kernel at kernel/Core/Services/. Most are used by the kernel or the package manager rather than called directly from your app.

Service Purpose
ArchiveService Archive operations (zip, tar)
GitService Git repository operations
InteractiveSelect Interactive CLI selection menus
ManifestService Module manifest management
ModuleMetadataService Module metadata management
RedirectHandlerService Handle redirect responses
RegistryReadmeService Read package readmes
RegistryService Package registry operations
SplashScreenService Command-line splash output
TemplateGenerator Code template generation
VersionService Version comparison and handling

Autoloader

The kernel's Autoloader (in kernel/Core/Autoloader.php) implements PSR-4 autoloading for your app, the kernel, and installed modules.

Namespace mapping

Namespaces are mapped to base directories:

  • appBASE_PATH/app
  • forgeBASE_PATH/kernel
  • modulesBASE_PATH/modules

File existence caching

To avoid repeated file-system lookups, the autoloader keeps a class file map in memory and persists it to storage/framework/cache/class_file_map.php between requests. The persistent map is capped at 8,000 entries.

Adding paths

Register additional namespace paths programmatically.

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

Bootstrap Process Internal

The bootstrap boots the kernel on every request. You normally do not call these classes directly; they run automatically when your front controller invokes Kernel::init(). The orchestrator and setup classes live in kernel/Core/Bootstrap/.

Entry point

Calling Kernel::init() delegates to the singleton Bootstrap, which loads the environment, runs each setup class, and guards your .env file from direct HTTP access.

Setup classes

ServiceDiscoverSetup

Discovers #[Injectable] classes and registers them with the container.

KernelServiceSetup

Registers the kernel's own services with the container.

ModuleSetup

Loads installed modules from the modules directory.

ContainerAppSetup

Initializes the container for web (app) context.

ContainerCLISetup

Initializes the container for CLI context.

ErrorHandlerSetup

Wires up error and exception handling.

SessionSetup

Initializes session handling.

AppCommandSetup

Discovers and registers application console commands.

LoadsCommands

Loads kernel and module commands.

LoadsIncludes

Includes helper and support files.

CliErrorHandler

Handles errors raised in CLI context.

Cache System

The cache system provides method-level caching with automatic proxy generation. Use the cache() helper or resolve CacheManager from the container.

Drivers

Three drivers are available; the default is SQLite.

  • SQLite (default): persists to storage/database/cache.sqlite
  • File: writes storage/framework/cache/<key>.cache files
  • Memory: in-memory, per request only

Choose the driver with the CACHE_DRIVER environment variable.

Reading and writing

Use the cache() helper for single keys, or resolve the cache manager to use tags.

// Single keys
cache('api.weather', $weather, 3600);
$weather = cache('api.weather');

// Tagged cache via the manager
$cache = Container::getInstance()->make(CacheManager::class);
$cache->tags(['users', 'profile'])->set('user:123', $user);
$cache->clearTag('users');

Cache attributes

Annotate a method with #[Cache] for automatic caching; annotate with #[NoCache] to opt a method out.

use Forge\Core\Cache\Attributes\Cache;

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

Proxy generation

Services with cached methods are wrapped in runtime-generated proxies (ProxyGenerator) so the interceptor (CacheInterceptor) manages lookups without reflection on every call.

  • Proxies are generated once per class and reused across requests
  • They extend the original class and implement ProxyMarkerInterface
  • Cached methods resolve through the interceptor

Building your app

These are the kernel primitives. To actually serve a web app, plug in capabilities — they build on the primitives above: