denetorus / galaxy-application
Runs an application through ordered stages and returns a shared result. Use it to assemble a new entry point or transport.
Requires
- php: >=8.4
- denetorus/galaxy-result: ^0.3.0
- psr/container: ^2.0
Requires (Dev)
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-03 12:09:53 UTC
README
Runs an application through ordered stages and returns a shared result. Use it to assemble a new entry point or transport.
Русский · Architecture · MIT
Getting started
Requires PHP 8.4 or newer. Install version 0.1.0 from Packagist.
composer require denetorus/galaxy-application:0.1.0
From the source checkout, install dependencies and run
composer install php examples/run.php
Complete example examples/run.php.
GApp merges defaults and explicit configuration, builds the container, runs stages in order and cleans up request state. Stages are created without arguments and can use active application data, the shared result and request ID. PrepareInputStage and AuthStage are optional. The application decides access policy. A stage exception is recorded and later stages still execute. An initialization or cleanup failure can propagate as ApplicationFailure.
Run and stages
$result = App::run( root: dirname(__DIR__), input: ['command', '--flag'], stages: [FirstStage::class, SecondStage::class], );
GApp::run returns GResult. stages: null (or omission) selects the subclass's protected static defaultStages(): array.
An explicit list replaces defaults, and [] executes no stages and returns the initially empty GResult.
The base default is PresentationStage. Console and REST configure input preparation and their own ConsoleDispatchStage or RestApiDispatchStage before presentation.
A stage implements ApplicationStageInterface::execute(): void and is constructed with no arguments immediately
before execution. Ordered lists of instantiable implementation class names are validated before startup, without
constructing stages. Repeated classes are allowed and create fresh instances.
GApp always iterates the selected list after boot, even when the shared GResult contains business errors. Each stage decides whether to do work. DispatchStage implementations skip dispatch when errors already exist; PresentationStage still presents the result. An exception in a stage is recorded and the remaining stages are called.
Request lifecycle
- Start — GApp::run(). The entry point supplies the application root and optionally configuration, input, stages and a request ID. GApp validates the supplied ID or generates a UUID v4.
- Build and boot — GApp, ContainerBuilder, ApplicationData. GApp merges configuration, creates the shared GResult, builds the container and activates the run context before calling boot().
- Prepare input — PrepareInputStage. The environment prepares the input needed by later stages. Successful preparation updates execution.input. Input errors go into the shared result.
- Run optional stages — ApplicationStageInterface. Applications can add authentication, logging or other steps at positions that suit their workflow.
- Dispatch — DispatchStage. A concrete stage handles routing and merges any separate result into the shared GResult. It skips dispatch if the result already contains errors.
- Present — PresentationStage and PresenterInterface. The presenter receives the shared GResult and emits the output for the entry point. Further stages can run after presentation.
- Clean up — GApp. GApp runs deferred cleanup in reverse registration order, releases the context and returns the shared GResult on normal completion.
A typical dispatch sequence:
DispatchStage::execute()
→ dispatch() in the concrete stage
→ GRouter selects an adapter when a route table is used
→ AdapterInterface::dispatch() hands input to the runner
→ Runner selects the controller and action
→ ControllerConstructorInterface obtains the controller where supported
→ the Controller action returns GResult
→ DispatchStage merges the result into the shared GResult
The application selects the stage sequence. Base GApp defaults to PresentationStage. Exceptions from individual stages are recorded in the shared result and the sequence continues.
Execution data
ApplicationData is a general-purpose key/value store; GApp reserves its execution section for the current run:
input: the input array, after defaultInput/validateInput;result: the shared GResult, initialized before container construction and boot;entry: the effective merged entry configuration and custom options;
public function execute(): void { $execution = GApp::data()->get('execution'); $execution['result']->addMessage('Stage completed.'); }
Stages mutate the shared result instead of replacing it. Replacement is rejected after stage execution. DispatchStage copies returned data/messages/warnings/errors into that result (without clearing the source). UIDs and console codes follow GalaxyResult copy rules; originPath gains the application receiver name. Earlier messages, warnings and data are retained according to normal GResult merge rules. PresentationStage passes the same shared result to PresenterInterface::present(GResult): void. The result returned by dispatch need not be the same object as the final shared result.
ApplicationData::get returns ordinary PHP array values; when changing the execution array itself, write it back
with set(). The GResult object inside the array is shared and can be changed directly.
Applications define additional settings in common.data or entry.options. They must not repurpose execution.
No ready/events keys are generated.
Extending the application
GApp is inheritable. Final static runtime methods: run/data/container/application/isActive/path/requestId/uuid. The protected constructor is final. Hooks: getDefaultApplicationConfig/getDefaultEntryConfig/defaultInput/validateInput/validateEntry/defaultStages, buildContainer/boot. final protected entry(): array exposes effective settings during the active lifecycle. DispatchStage is abstract. A routing stage implements dispatch(array): GResult and reads effective settings from execution.entry; the application selects the stage in its stage sequence.
Configuration may be an array or root-relative PHP file returning an array. Map values merge recursively; lists (including []) and scalar/object values replace. Named name/presenter override run options, which override entry configuration and class defaults. For names, explicit applicationConfig takes priority over entryConfig. Common keys: name/data/services. Base entry keys: presenter/options/name; presenter is optional until PresentationStage runs. The presenter is a class with no required constructor arguments, or an explicitly constructed PresenterInterface object. NullPresenter provides no output. Custom stage lists need not include a presenter.
applicationConfig, entryConfig, input, name and presenter use null for defaults. input must otherwise be an array; explicit [] bypasses defaultInput. Base defaultInput returns [], console defaults read argv without the script name. Objects/scalars as the entire input are rejected. Empty name '' and explicit config arrays retain their meaning.
An explicit existing absolute root is required. APP_ROOT is bound before defaults/config files are evaluated. path() resolves existing regular files inside the root and rejects traversal/escaping paths. The same root may be reused sequentially; another root in the same process is rejected. Nested or overlapping runs are unsupported; the shared guard covers stage execution, cleanup and reference release.
Container and data
Container implements PSR-11. ContainerBuilder supports bind(id, Closure), singleton(id, Closure|string|null), instance(id, object), named constructor arguments and an optional construction observer. The builder is sealed after build. Unregistered concrete classes are autowired lazily, interfaces need bindings, scalar arguments need explicit values/defaults. Class dependencies are resolved before constructor defaults. Unsupported union/intersection/variadic constructors fail explicitly. Explicit registrations have priority; getDefinitions lists explicit IDs, lifetime and state without creating services. Missing requested services produce NotFound; missing dependencies produce ServiceResolutionException with the cause. Classified container exceptions are preserved, cycles detected and failed stack frames released.
The default buildContainer registers the run-owned ApplicationData and calls common.services(Closure) once before build. ApplicationData provides exact string-key has/get/set/remove/clear. Missing keys throw OutOfBoundsException; null is distinct from absence. Normal PHP value/reference semantics and shallow cloning apply; serialization is rejected.
Cleanup and failures
GApp builds the container, invokes boot, executes the stage list and always performs registered cleanup. boot receives a defer registrar valid only during that invocation. Cleanup executes LIFO once, continues after callback/destructor failures, and collects all causes. Saved registrars stay invalid in later runs and after failed boot. Presentation occurs before cleanup; the active facade remains available during cleanup, then owned references are released. No disposal API is invoked implicitly, and input generators are not consumed by GApp.
ApplicationFailure exposes phase boot/execute/shutdown, the primary exception and ordered cleanup errors. Its previous exception is the primary cause, or the first cleanup error for cleanup-only failure. Errors releasing stage/presenter/container/data/runtime are preserved. Configuration/build errors retain their native type when there are no cleanup errors. Business errors recorded in GResult do not throw or stop the stage loop.
Checks
composer install php vendor/bin/phpunit php tests/smoke.php vendor/autoload.php php tests/generic-missing.php vendor/autoload.php php tests/container.php vendor/autoload.php
Lifecycle stages and their interface are in src/Stages (Galaxy\Application\Stages). Component exceptions are in src/Exception. Interface names end with Interface.
Request identifier
The optional LAST parameter GApp::run(..., ?string $requestId = null) identifies one application invocation. Null generates a new UUID v4 from random_bytes(16), setting version4 and RFC9562 variant bits. Supplied IDs must be exactly36 characters: lowercase hex in8-4-4-4-12 form, version4 and variant8/9/a/b. Example:919108f7-52d1-4320-9bac-f847db4148a8. Whitespace, uppercase, braces, URNs, nil and other versions are rejected. InvalidArgumentException is raised before root binding, configuration or lifecycle execution; no normalization occurs. The ID belongs to the runtime, independently of logging, and cannot be replaced through ApplicationData. Final GApp::requestId():string is available while the context is active:boot, stages, presenter and cleanup. Before activation (including container construction), outside run, and after completion/failure it throws LogicException. Sequential runs generate fresh IDs unless explicitly supplied; callers own uniqueness of supplied IDs. Nested runs remain forbidden and do not replace the active ID. Subclasses share the same accessor. The ID is not automatically added to GResult, HTTP headers or logs; those remain separate integration concerns.
UUID generation
Final GApp::uuid():string creates a new canonical lowercase UUID v4 for arbitrary application needs. It works before, during and after run without activating or changing runtime, requestId or ApplicationData. run uses uuid() when requestId is null; supplied requestId values are only validated. Subsequent uuid() calls never change the active request ID. random_bytes failures propagate to the caller.
Stage exception handling
Every configured stage is attempted in order, even after another stage fails. Constructor, execute and immediate stage-release exceptions add a framework error 6 (consoleCode 2, category internal) to the shared GResult. Stages decide whether to skip their own work when that result already contains errors. Existing errors and their priority are preserved; replacing/removing the shared result is recorded as a failure and the original is restored. Later stages and cleanup can inspect execution.stageFailures: an ordered list of stage (class), phase (construct/execute/release) and exception (the original Throwable). PresentationStage may supply an ApplicationFailure wrapper preserving the original presenter cause and release exceptions. These diagnostics are runtime-only; they are not automatically copied into GResult, output or logs and may contain sensitive exception details. The public error has a fixed safe text, stage class and phase, without exception messages or traces. Boot, configuration, container construction and final cleanup/release failures retain their exception behavior. A failed presenter does not produce a second presentation attempt; subsequent configured stages still run.
Authentication primitives
Galaxy\Application\Auth\GAuth returns a fresh guest UserIdentity. Extend authenticate(array $input = []): UserIdentity to verify application credentials. UserIdentity is inheritable and readonly; its private authenticated flag is set only in the constructor, independently of id, and read through final isAuthenticated(). Tokens/passwords must not be stored in attributes. No authentication stage runs automatically: the application chooses when to authenticate and whether to allow guests. Standalone checks: php tests/auth.php.
GalaxyResult 0.3: read business codes with getBusinessCode(). DispatchStage uses copyData/copyMessages/copyWarnings/copyErrors and preserves the source GResult; it does not use move operations or legacy API aliases.
Vocabulary
| Entity | Meaning |
|---|---|
| Application | The running GApp instance or subclass. |
| ApplicationRun | One call to GApp::run(). |
| ApplicationRoot | The root directory for application paths. |
| ApplicationConfig | Shared settings for name, initial data and services. Passed as applicationConfig. |
| EntryConfig | Settings for the selected entry point. |
| ApplicationInput | The input array for a run. |
| RequestId | The UUID v4 identifying the run. |
| ApplicationData | The keyed store available during a run. |
| ApplicationStage | A lifecycle step implementing ApplicationStageInterface. |
| StageSequence | The ordered list of stages. |
| ApplicationResult | The GResult returned by a run. |
| StageFailure | An exception captured during a stage. |
| ApplicationFailure | A lifecycle exception carrying the failure phase and underlying exceptions. |
| Presenter | Presents the GResult through the entry point. |
| Container | Resolves services by identifier. |
| ContainerBuilder | Collects registrations and builds the container. |
| ServiceDefinition | A registration describing a service identifier and lifetime. |
| ServiceFactory | Creates a service when it is resolved. |
| UserIdentity | Holds the resolved user identity and authentication state. |
getDefaultApplicationConfig() and getDefaultEntryConfig() supply defaults. Later settings override matching keys. mergeConfigs() merges nested maps and replaces lists as a whole.
PrepareInputStage is a reusable input preparation stage. Its prepareInput() hook receives the input array and the shared GResult. A prepared array replaces execution.input on success. A handler can record an input error in GResult and return null.
After activation, GApp calls logRequestStart() before boot and logRequestFinish() after deferred cleanup, while the run context is active. The base hooks are no-ops. The finish hook takes no arguments. It reads the shared result, stageFailures and lifecycleFailure from execution. lifecycleFailure is null unless the lifecycle fails, for example during boot or deferred cleanup. An exception raised by a logging hook becomes warning 7. Failures before activation or after context release are outside these hooks.
Authentication stage
To authenticate a request, place Galaxy\Application\Stages\AuthStage after input preparation and before access checks or dispatch. AuthStage resolves GAuth from the container, passes execution.input to it and stores the UserIdentity at GApp::data()->get('auth'). The default GAuth returns a guest identity. Register a custom service under GAuth::class in the services configuration. If an earlier stage recorded an error, AuthStage stores a guest identity and skips the service call. Access policy belongs to the application.