Skip to content

API Reference

Ray Fung edited this page Feb 26, 2026 · 4 revisions

API Reference

Complete class reference for the Razy Framework. Click any class to view detailed documentation with method signatures, usage examples, and scenarios.

Core (Internal) Internal

These classes are internal framework components. They are not typically used directly by module developers.

Application

Framework boot and request lifecycle manager. Lazy initialization — no I/O in constructor.

Container

PSR-11 DI container with auto-wiring, singleton/transient bindings, alias support

Distributor

Site distributor loader and module coordinator. Delegates to ModuleRegistry, ModuleScanner, PrerequisiteResolver, RouteDispatcher.

Module

Module lifecycle and dependency resolver

Domain

Domain matching and routing bridge (7 methods: construct, getAlias, getDomainName, matchQuery, autoload, getDistributor, dispose)

Error

Error handling and display — delegates rendering to ErrorRenderer

ErrorRenderer

HTML/CLI error page rendering (extracted from Error)

ErrorConfig

Static error configuration management (debug mode, cached errors)

PackageManager

Package dependency resolution

ConfigLoader

Mockable configuration file loader (replaces direct require calls)

Module Development

Controller

Module controller with 13 lifecycle hooks, utility methods, and DI access via resolve()/hasService()

Agent

Route/event/API registration in __onInit

ModuleInfo

Read-only module metadata with lazy initialization (16 methods)

Data & Storage

Database

Multi-driver database with Statement builder, WhereSyntax, TableJoinSyntax

Collection

Enhanced ArrayObject with dot-path access

Configuration

Auto-loading config files (.php/.json/.ini/.yaml)

HashMap

Hash-indexed object registry (ArrayAccess/Iterator/Countable)

YAML

YAML parser and dumper (4 static methods)

Rendering

Template

Template engine with blocks, function tags, modifiers, Entity system

DOM

Programmatic HTML builder

IO & Communication

XHR

JSON API response builder with CORS

SSE

Server-Sent Events streaming and proxying

Mailer

SMTP email with TLS/SSL, async sending

SimplifiedMessage

STOMP-like message protocol

FileReader

Sequential multi-file line reader

Security

Crypt

AES-256-CBC encryption (2 static methods)

Advanced

ThreadManager

Concurrent process execution with queue

Thread

Individual thread state machine

SimpleSyntax

Query DSL parser (ParseSyntax, ParseParens)

RepoInstaller

GitHub repository module installer

RepositoryManager

Repository index generator

PluginManager

Centralized plugin registry for Template, Collection, Statement, Pipeline

Database Sub-classes

Statement

Fluent SQL query builder

StatementExecutor

Query execution — separated from building

LazyResultSet

Lazy-loading result processing (lazy, lazyGroup, lazyKeyValuePair)

Query

Result set iterator

Table

Schema definition and ALTER

Column

Column type definition

WhereSyntax

WHERE clause DSL parser

TableJoinSyntax

JOIN clause DSL parser

Driver

Abstract database driver

Statement Builders (Strategy Pattern)

SelectSyntaxBuilder

Builds SELECT SQL syntax

InsertSyntaxBuilder

Builds INSERT/REPLACE SQL syntax

UpdateSyntaxBuilder

Builds UPDATE SQL syntax

DeleteSyntaxBuilder

Builds DELETE SQL syntax

StatementType

Enum: Select, Insert, Update, Delete, Raw, Replace

Template Sub-classes

Source

Parsed template source

Block

Template block definition

Entity

Block instance with data binding

CompiledTemplate

Pre-tokenized template for fast repeated rendering

Distributor Sub-classes

ModuleRegistry

Tracks loaded modules, API registrations, lifecycle queue

ModuleScanner

Filesystem module discovery and manifest caching

PrerequisiteResolver

Package version constraints and conflict resolution

RouteDispatcher

Route registration and URL matching/dispatching

Module Sub-classes

ModuleStatus

Enum: Failed, Disabled, Unloaded, Pending, Initialing, Processing, InQueue, Loaded

ClosureLoader

Loads and caches closure files from module controller directories

CommandRegistry

API and bridge command registration and execution

EventDispatcher

Per-module event listener registration and dispatching

Contracts (Interfaces)

| Interface | Extends | Purpose |

| --- | --- | --- |

| ContainerInterface | Psr\Container\ContainerInterface (PSR-11) | DI container contract |

| CacheInterface | Psr\SimpleCache\CacheInterface (PSR-16) | Simple cache contract |

| DatabaseInterface | — | Core database access |

| EventDispatcherInterface | — | Event dispatcher |

| ModuleInterface | — | Module instance |

| TemplateInterface | — | Template engine |

Exception Hierarchy

| Exception | Extends | Purpose |

| --- | --- | --- |

| HttpException | RuntimeException | Base HTTP error |

| RedirectException | HttpException | HTTP redirect (replaces exit) |

| NotFoundException | HttpException | 404 Not Found |

| ConfigurationException | RuntimeException | Config loading/parsing errors |

| DatabaseException | RuntimeException | Base database error |

| ConnectionException | DatabaseException | DB connection failures |

| QueryException | DatabaseException | SQL execution errors |

| TemplateException | RuntimeException | Template parsing/rendering |

| ModuleException | RuntimeException | Base module error |

| ModuleLoadException | ModuleException | Module load failures |

| ModuleConfigException | ModuleException | Invalid module config |

| CacheException | RuntimeException | Cache driver errors |

| NetworkException | RuntimeException | Base network error |

| FTPException | NetworkException | FTP operation errors |

| SSHException | NetworkException | SSH/SFTP errors |

| ContainerException | RuntimeException | DI container errors (PSR-11) |

| ContainerNotFoundException | ContainerException | Entry not found (PSR-11) |

Utility Classes

| Class | Purpose |

| --- | --- |

| ArrayUtil | Array manipulation (construct, refactor, compare, wrap) |

| DateUtil | Date calculations (future weekday, day diff) |

| NetworkUtil | SSL detection, IP retrieval, FQDN validation |

| PathUtil | Path tidy, append, resolve, fix traversals |

| StringUtil | GUID generation, JSON validation, file size formatting |

| VersionUtil | Semantic version comparison with range operators |

Quick Usage Examples

Controller & Agent (Module Setup)

// controller/my_module.php → Main controller

return new class extends Controller {

    protected function __onInit(Agent $agent): bool

    {

        // Register routes

        $agent->addRoute('/', 'index');

        $agent->addRoute('/user/(:d)', 'user');       // :d = digits only

        $agent->addRoute('/search/(:a)', 'search');    // :a = any characters



        // Register API commands (callable by other modules)

        $agent->addAPICommand('getData', 'api/getData');

        $agent->addAPICommand('submit', 'api/submit');



        // Listen to framework events

        $agent->listen('onReady', 'events/ready');



        // Middleware

        $agent->middleware(function ($request, $next) {

            // Pre-processing

            return $next($request);

        });



        return true;

    }



    protected function __onReady(): void

    {

        // All modules loaded → safe to use cross-module APIs

    }

};

Route Handler Closure

// controller/my_module.index.php

return function () {

    $template = $this->loadTemplate('main');

    $template->assign('title', 'Welcome');

    echo $template->output();

};



// controller/my_module.user.php → with captured parameter

return function (string $userId) {

    $xhr = $this->xhr();

    $xhr->setData(['id' => $userId, 'name' => 'Alice']);

    return $xhr;

};

Cross-Module API

// Call another module's API from any controller method

$result = $this->api('other_module')->getData(['id' => 42]);



// API command handler: controller/api/getData.php

return function () {

    $params = func_get_args();

    return ['status' => 'ok', 'data' => $params[0] ?? null];

};

Database Queries

// Get database via DI container

$db = $this->resolve(\Razy\Database::class);



// SELECT with fluent builder

$users = $db->prepare()

    ->select('id, name, email')

    ->from('users')

    ->where('active=:active')

    ->order('<name')            // '<' = ASC, '>' = DESC

    ->limit(0, 20)

    ->lazyGroup(['active' => 1]);



// INSERT

$stmt = $db->insert('users', ['name', 'email']);

$stmt->assign(['name' => 'Alice', 'email' => 'alice@example.com']);

$db->execute($stmt);

$newId = $db->lastID();



// UPDATE with increment

$stmt = $db->update('users', ['name', 'login_count++']);

$stmt->where('id=:id');

$stmt->assign(['name' => 'Bob', 'id' => 1]);

$db->execute($stmt);



// Transaction

$db->transaction(function () use ($db) {

    $db->execute($db->insert('orders', ['user_id', 'total'])

        ->assign(['user_id' => 1, 'total' => 99.99]));

    $db->execute($db->update('users', ['order_count++'])

        ->where('id=:id')

        ->assign(['id' => 1]));

});

Collection (Dot-Path Access)

use Razy\Collection;



$data = new Collection([

    'app' => [

        'name' => 'MyApp',

        'settings' => ['debug' => true, 'version' => '1.0'],

    ],

]);



// Dot-path selector

$name  = $data('app.name');                // → 'MyApp'

$debug = $data('app.settings.debug');      // → true



// Modify nested values

$data->set('app.settings.debug', false);

Template Engine

// Load and render a template

$tpl = $this->loadTemplate('main');

$tpl->assign('title', 'Hello World');

$tpl->assign('items', ['Apple', 'Banana', 'Cherry']);

echo $tpl->output();



// Template file (view/main.tpl):

// <h1>{$title}</h1>

// <!-- BEGIN BLOCK items -->

// <li>{$value}</li>

// <!-- END BLOCK items -->

DI Container

// Register a service in __onInit

$agent->container()?->singleton(CacheInterface::class, FileAdapter::class);

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



// Resolve in any controller method

$cache  = $this->resolve(CacheInterface::class);

$logger = $this->resolve(LoggerInterface::class);



// Check if a service exists

if ($this->hasService(CacheInterface::class)) {

    $cache = $this->resolve(CacheInterface::class);

}

XHR (JSON Response)

// In a route handler

return function () {

    $xhr = $this->xhr();

    $xhr->setHeader('success', true);

    $xhr->setData(['users' => [['id' => 1, 'name' => 'Alice']]]);

    return $xhr;

};

// Output: {"success":true,"data":{"users":[{"id":1,"name":"Alice"}]}}

Encryption

use Razy\Crypt;



// Encrypt / Decrypt with AES-256-CBC

$encrypted = Crypt::encrypt('sensitive data', 'my-secret-key');

$decrypted = Crypt::decrypt($encrypted, 'my-secret-key');

// → 'sensitive data'

← Previous CLI Commands

Next → ModuleInfo

Clone this wiki locally