Architecture
How Azera fits together – from the AppContext service container to the MVC layer, the database abstraction, and the CLI tools.
Core Principles
- Lightweight runtime with minimal mandatory dependencies
- Explicit routing and dispatch
- Unified query API for model and table workflows
- Read/write DB separation support
- Simple composition through
AppContext
Main Components
AppContext
Central runtime context and service container – accessed as a singleton via AppContext::instance().
Built-in lazy service accessors:
| Method | Returns |
|---|---|
request() |
Azera\Http\Request |
view() |
Azera\Core\ViewEngine |
session() |
Azera\Http\Session|null |
cookies() |
Azera\Http\Cookies — reads via request()->cookies(), emits what was written |
dbManager() |
Azera\Db\DatabaseManager |
route() |
Azera\Core\ResolvedRoute|null – populated by Dispatcher |
logger() |
Psr\Log\LoggerInterface – NullLogger by default |
events() |
Psr\EventDispatcher\EventDispatcherInterface – NullEventDispatcher by default |
cache() |
Psr\SimpleCache\CacheInterface – NullCache by default |
queue() |
Azera\Queue\QueueInterface – throws if unregistered |
config() |
Azera\Config\Config – lazily created |
Custom services can be registered with $ctx->set($id, new MyService()) or $ctx->set($id, fn() => new MyService()) and retrieved with $ctx->get($id). Registered callables are treated as zero-argument lazy factories and cached on first resolution. Auto-wiring is supported: unregistered class names are instantiated via reflection with their constructor dependencies resolved recursively from the container.
MVC Layer
Routermatches URI + method to route patterns, extracting typed parameters; supports named routes, inline or scoped groups (prefix(),namespace(),controller(),middleware()), and custom parameter validators.match()returnsnullfor both an unknown path and a known path with the wrong method;allowedMethods()tells them apart (null versus a list) for callers that want to answer 405 instead of 404Kernel(optional) coordinatesRouterandDispatcherfor one request and owns the 404/405/500 policy: a missing route answers throughNotFoundHandlerInterface, a wrong method answers 405 withAllow, and an exception answers throughErrorHandlerInterface. It never writes output, so the same call serves FPM and a resident workerDispatchertakes no constructor arguments and obtainsAppContextinternally. It resolves the controller class from the route and stores route data withAppContext::setRoute(). Global and route-group middleware run first; if they allow the request, the controller is constructed via DI (AppContext::get()). Controller and action middleware then run, and action parameters (route variables or DI) are resolved in the innermost stage immediately before invocationControllerprovides access to request/context plus controller- and action-level middleware declarationsViewEnginerenders templates, layouts, and namespaced views; supports global view variables and partial renderingModelMappingmaps logical model names to PHP classes and table names – useful when decoupling route/query naming from class namesMiddlewareInterfacedefines the contract for all middleware;SessionMiddlewareis the built-in implementationResolvedRoute(inAppContext->route()) contains resolved route information accessible anywhere
Data Layer
Model(Azera\Orm) provides Active Record style methods (find,findAll,create,save,upsert,delete, …) delegating to theEntityManager— identity-mapped reads, diff-based writes, heap-backed state tracking (hasChanged/loadState)Queryis the fluent SQL builder for select, write, count, and exists operations; terminal calls (insert,upsert,update,delete) finalize the queryDatabasewraps PDO with transaction helpers and lazy connection creationResultSetprovides iterable, countable access to model or raw-row resultsPaginatorwraps aQuerybuilder to add page/offset/total metadata with minimal boilerplateCondition,Sql, andSqlCaseprovide composable SQL fragments and safe escape hatches (Sql::bind()for PDO-bound values)
CLI Layer
Consolemaps CLI arguments toTaskclasses and*Action()methods; additional namespaces can be registered for discoveryTaskis the base class for all commandsModelSyncTaskis the built-in task that drives model synchronisation (see Sync Layer below)
Request Flow (Web)
HTTP Request
-> Kernel::handle() (optional; skip it to call the two below directly)
-> Router::match()
-> Dispatcher::dispatch(routeInfo)
-> Controller action
-> Response
For controller return-value mapping, see Controllers & Views. For the 404/405/500 policy the Kernel owns, see MVC Routing.
Data Flow
Two entry points into the database: models for object-oriented work, Query for direct table access.
// Model-centric
$user = User::find(10);
$rows = User::query()->where('status', 'active')->select();
// Table-centric
$rows = Azera\Db\Query::raw()
->table('users')
->where('status', 'active')
->select();
Write operations are terminal builder calls (insert, upsert, update, delete).
Read/Write Separation
Azera supports replica setups through DatabaseManager roles.
Register named connections in bootstrap:
$mgr = $ctx->dbManager();
$mgr->set('write', new Database('mysql:host=primary;dbname=app', 'rw', 'secret'));
$mgr->set('read', fn() => new Database('mysql:host=replica;dbname=app', 'ro', 'secret'));
Models read from the read role and write to the write role by default, falling back to the registered default when the role is absent. Per-model overrides:
User::setDefaultReadRole('replica');
User::setDefaultWriteRole('primary');
User::setDefaultRole('analytics'); // both read + write
For single-database apps, register one connection under any name – models fall through to the default automatically:
$ctx->dbManager()->set('default', new Database(...));
Enterprise Subsystems
Azera provides opt-in enterprise subsystems that use PSR interfaces directly (no adapters needed):
| Subsystem | PSR | Accessor | Default |
|---|---|---|---|
| Logging | PSR-3 | logger() |
NullLogger |
| Events | PSR-14 | events() |
NullEventDispatcher |
| Cache | PSR-16 | cache() |
NullCache |
| Queue | — | queue() |
throws if unregistered |
| Config | — | config() |
empty Config |
Two more defaults are resolved by interface rather than by accessor, because only the Kernel consumes them:
| Service | Interface | Default |
|---|---|---|
| 404 policy | NotFoundHandlerInterface |
PlainNotFoundHandler |
| error policy | ErrorHandlerInterface |
PlainErrorHandler |
All subsystems are zero-cost when unused — each accessor lazily returns a no-op default, so calling code can always invoke $ctx->logger()->info(...) or $ctx->events()->dispatch(...) without null-checks. Register real implementations via $ctx->set(InterfaceClass::class, $factory) to activate them.
AOP (Aspect-Oriented Programming)
Azera supports declarative cross-cutting concerns via PHP 8 attributes:
#[Advised]marks a class for proxy generation#[Transactional]wraps methods in DB transactions#[Cache]caches method return values#[Retry]retries on failure with backoff#[Log]logs method entry/exit/duration
The ProxyFactory generates file-based proxy classes (OPcache'd) that extend the target and wrap advised methods. Services must be autowired (class string, not factory) for proxy generation. See AOP.
Security
CsrfMiddleware— synchronizer token pattern, implementsMiddlewareInterfaceRateLimiter— cache-backed, fixed-window rate limitingHasher— password hashing (PHPpassword_hash/password_verify)AuthManagerInterface/GuardInterface— authentication contracts
See Security.
Sync Layer
Azera ships a code-generation and schema-synchronisation subsystem under Azera\Sync. It introspects a live database and updates (or generates) Model PHP files to match the schema, without requiring a separate migration runner.
Key components:
SyncRunner– orchestrates the sync: reads schema, diffs against the parsed model, applies or previews changesModelParser– parses an existing PHP model file into aParsedModelwith typed properties and accessorsModelDiff– computes the diff between the live schema and the parsed model (add/remove/change columns and accessors)CodeGenerator– writes the updated PHP source back to the model fileSyncOptions/SyncResult– configure dry-run/preview mode and carry the result back to the callerSchema\– driver-specific providers (MySqlSchemaProvider,PostgresSchemaProvider,SqliteSchemaProvider) that return a normalisedTableSchema
The CLI entry point is the built-in ModelSyncTask; the same SyncRunner API can be called programmatically.
Extensibility Points
- Router custom parameter validators via
type() - Router route groups via inline or scoped
prefix(),namespace(),controller(), andmiddleware() - Dispatcher middleware groups and controller factory
- Model overrides:
source(),schema(),idFields(),readConnection(),writeConnection() - Query SQL escape hatches via
Sqlnodes (Sql::bind()for PDO-bound params) - PSR-3 logger: register any
Psr\Log\LoggerInterfaceimplementation via$ctx->set() - PSR-14 events: register any
Psr\EventDispatcher\EventDispatcherInterface, listen to typed events - PSR-16 cache: register any
Psr\SimpleCache\CacheInterfaceimplementation - Queue: register any
Azera\Queue\QueueInterfaceimplementation (SyncQueue or async driver) - AOP interceptors:
registerInterceptor(AdviceClass::class, $interceptor)for custom advice attributes - Security:
CsrfMiddleware,RateLimiter,Hasher, customGuardInterfaceimplementations