Index

Application

MMO\core · 1 symbol · generated 5 Oct 2026

class

Application

Application.php:62
This is the main module of the framework: - listen on the php signals : shutdown, error, exception, autoload - route request and send response to the server - log everything - plan jobs (CRON like)final class MMO\core\Application extends MMO\core\classes\aModule implements Psr\Http\Server\RequestHandlerInterface
Namespace
MMO\core
Extends
aModule
Implements
RequestHandlerInterface
> NOTE: to print directly the logs on screen in realtime use the configuration: `stream: stdout` ### Router The application route and handle any request. You can call `\MMO\run()` to route the current request or pass a request as argument to run your custom request. When run, the application follow these steps: 1. create a `\MMO\core\server\Route` holding the current request and all the middlewares (function to call with the route) that match the current request's url. 2. dispatch the route, so it can be altered (remove/add middleware, set a default response, add request's attribute, etc..) 3. execute the middleware (that should create/alter the response) 4. dispatch the final response 5. send the response to the server 6. exit > Note: It is a good idea to listen to the event `\MMO\core\server\Route` when you want to execute generic behavior before any controller. (like checking for updates) ` MMO\core\server\Route::AddListener(function (Route $route) {..});` > Note: Listen to the event `\MMO\core\server\Response` to execute behavior just before the response is sent to the server. ` MMO\core\server\Response::AddListener(function (Response $response) {..});` ### Jobs The application allow to register jobs to do if certain conditions are met. A job has a trigger function (a test that indicates if the jobs needs to be activated), and an action function (the job). These functions take no arguments. The trigger function MUST return a boolean. The jobs are tested during 4 phases of the application. You can set them up for one or multiple phases, combining the flags with the binary operator `|`. - PHASE_START: job is executed just after the application has been waked up - PHASE_RUN: job is executed just after the route has been dispatched - PHASE_RESPONSE: job is executed just before the response is sent to the server - PHASE_SHUTDOWN: job is executed just before the application shutdown (WARNING: not safe for long job) - PHASE_EXCEPTION: job is executed when an exception is not caught

Index

OPENAPI_VERSION
PHASE_EXCEPTIONjob is executed when an exception is not caught
PHASE_RESPONSEjob is executed just before the response is sent to the server
PHASE_RUNjob is executed just after the route has been dispatched
PHASE_SHUTDOWNjob is executed just before the application shutdown (WARNING: not safe for long job)
PHASE_STARTjob is executed just after the application has been waked up
autoloadtells if application capture autoload
errorstells if application capture errors/exceptions
exceptionthe last exception encountered
inc
infoApplication information (for API)
jobs
logs
pathsPaths aliases
phase
printercurrent text dumper
response
route
routes{string: [\MMO\core\attributes\APIRoute]} the key is a group id (generally a classname)
sortJobs
streamthe stream to write the logs in
absoluteFilename($uri, $base)Generate a valid absolute filename, resolving path.
absoluteUrl($uri, $base)Generate a valid absolute url, resolving path.
addInfo($info)Merge extra info (title/description/contact/...) into $info, used by api's OpenAPI document.
addJob($trigger, $job, $when, $priority)Register a job: $trigger is checked (and $job run if it returns true) during executeJobs, called once per phase this application goes through (PHASE_START/PHASE_RUN/PHASE_RESPONSE/
addJobs($jobs)
addLog($log)Write log in the log stream (if any) or add it to the pool.
addRoute($groupId, $route)Add one more route to $groupId (creating the group if needed), on top of whatever connectRoutes already extracted.
api()
captureAutoload($capture)Set/unset php autoload hook
captureErrors($capture)Set/unset php error hook
classUrl($class, $extension, $resolve)Convert a classname/namespace into an uri with an path
clearLogs($disableLogs)
clearRoutes()Remove every registered route.
connectRoutes($class, $config)Connect route of a class or a function
createErrorResponse($e)Called by the route when an exception occurs, or by the php exception handler.
DefaultConfig() static
dump($values)Dump $values using whichever printer matches the current response's content type (falling back to $printer before any response exists).
executeJobs($when)Run every job (addJob) whose trigger currently returns true and whose $when includes $when; a job throwing is logged, not propagated.
extractRoutes($class, $config)Extract api routes from a function/class attributes
findRoute($groupId, $operation)
getDescription()
getIcon()
getIncludes()
getJobs($when, $executeTrigger)
getJobTrigger($job)
getLogs($flush)Get and flush the logs in the pool.
getPath($path)
getPaths($resolve)Get all alias for paths
getPhase()
getRequest()
getResponse()
getRoute()
getRoutes($groupId)
getTitle()
getTriggerJob($trigger)
getVersion()
getWorker($id, $regex)
getWorkerFile()
getWorkers()
handle($request)
hasRoutes($groupId)
isCapturingAutoload()
isCapturingErrors()
onAutoload($event)
phpAutoload($class)Magic php autoload handler Use directly spl_autoload_register
phpError($no, $str, $file, $line, $context)Magic php error handler Maps a raw PHP error (set_error_handler) to a log level and message, ignoring the @-suppression operator by design -- so an error a caller tried to silence via @ is…
phpException($e)Magic php exception handler Called for a truly uncaught exception (set_exception_handler) -- logs it, dispatches it if it's an
phpShutdown()Shutdown function call by register_shutdown_function WARNING: DO NOT call directly.
registerWorker($cmd, $pid)Record a background worker (runWorker) in the registry file (getWorkerFile), appending to it.
removeJob($fn)Remove a job from a trigger or a job
removeRoutes($groupId)
resolvePath($uri, $maxRecursivity)Resolve path recursively.
routeAPI($route)API endpoint serving api's OpenAPI document; stops further middleware so nothing else can alter it.
run($request)Run and exit the application
runInteractive($request)Run the application, executing middlewares and returns a Response or an exception
runWorker($cmd, $sleep)Start $cmd as a detached background process and register it (registerWorker).
sendResponse($response)Call this function to send a response
setDescription($value)
setIcon($icon)
setIncludes($pkgs)Include packages after the project and the application has been instantiated
setPath($path, $value)Set a path for an uri part A path xxx replace any uri parts named {xxx}
setPaths($paths, $isWindows)Set path for given paths.
setPhase($phase)Advance to $phase and run every job registered for it (executeJobs).
setRoutes($routes)
setStream($stream)Set the stream to write the logs in
setTitle($value)
__construct($config)
__wakeup()Registers this class's own routes (routeAPI) and advances to PHASE_START.

Constants6

OPENAPI_VERSION

const OPENAPI_VERSION = '3.0.3'

PHASE_EXCEPTION

job is executed when an exception is not caught

const PHASE_EXCEPTION = 16

PHASE_RESPONSE

job is executed just before the response is sent to the server

const PHASE_RESPONSE = 4

PHASE_RUN

job is executed just after the route has been dispatched

const PHASE_RUN = 2

PHASE_SHUTDOWN

job is executed just before the application shutdown (WARNING: not safe for long job)

const PHASE_SHUTDOWN = 8

PHASE_START

job is executed just after the application has been waked up

const PHASE_START = 1

Properties15

autoload

tells if application capture autoload

#[MMO\core\attributes\Serialize(unserialize: 'captureAutoload')] protected bool $autoload = false
Type
bool

errors

tells if application capture errors/exceptions

#[MMO\core\attributes\Serialize(unserialize: 'captureErrors')] protected bool $errors = false
Type
bool

exception

the last exception encountered

#[MMO\core\attributes\Serialize(false)] protected ?Throwable $exception = null
Type
null | Throwable

inc

#[MMO\core\attributes\Serialize(unserialize: 'setIncludes', order: 1000)] protected array $inc = []
Type
array

info

Application information (for API)

array $info = []
Type
array

jobs

#[MMO\core\attributes\Serialize(serialize: false, unserialize: 'addJobs', order: 1000)] protected array $jobs = []
Type
array

logs

#[MMO\core\attributes\Serialize(false)] protected array $logs = []
Type
array

paths

Paths aliases

#[MMO\core\attributes\Serialize(serialize: 'getPaths', unserialize: 'setPaths', order: -100)] protected array $paths = []
Type
array

phase

#[MMO\core\attributes\Serialize(false)] protected int $phase = 0
Type
int

printer

current text dumper

#[MMO\core\attributes\Serialize(order: -10)] MMO\core\printers\TextPrinter $printer
Type
TextPrinter

response

#[MMO\core\attributes\Serialize(false)] protected ?MMO\core\interfaces\iResponse $response = null
Type
null | iResponse

route

#[MMO\core\attributes\Serialize(false)] protected ?MMO\core\server\Route $route = null
Type
null | Route

routes

{string: [\MMO\core\attributes\APIRoute]} the key is a group id (generally a classname)

#[MMO\core\attributes\Serialize(unserialize: 'setRoutes', order: 100)] protected array $routes = []
Type
array

sortJobs

#[MMO\core\attributes\Serialize(false)] protected bool $sortJobs = false
Type
bool

stream

the stream to write the logs in

#[MMO\core\attributes\Serialize(unserialize: 'setStream', order: -9)] protected ?Psr\Http\Message\StreamInterface $stream = null
Type
null | StreamInterface

Methods68

absoluteFilename($uri, $base)

Application.php:641

Generate a valid absolute filename, resolving path.

function absoluteFilename(string $uri, string $base = '{root}'): stringAny relative filename is resolved using 'root' path by default. WARNING: absoluteUrl is resolved using baseurl by default. abolsuteFilename and absoluteUrl ARE NOT resolved from the same folder. If uri has an authority part, it is rebased using baseurl and basepath
$uristring
$base = '{root}'stringthe path to use to make the uri absolute
returnsstring

absoluteUrl($uri, $base)

Application.php:670

Generate a valid absolute url, resolving path.

function absoluteUrl(string $uri, string $base = '{siteurl}'): stringIf uri is absolute and has no authority, it is rebased using basepath as old base
$uristring
$base = '{siteurl}'stringthe base uri to use to resole the uri
returnsstring

addInfo($info)

Application.php:999

Merge extra info (title/description/contact/...) into $info, used by api's OpenAPI document.

function addInfo(array $info): void
$infoarray
returnsvoid

addJob($trigger, $job, $when, $priority)

Application.php:422

Register a job: $trigger is checked (and $job run if it returns true) during executeJobs, called once per phase this application goes through (PHASE_START/PHASE_RUN/PHASE_RESPONSE/

function addJob( callable $trigger, callable $job, int $when = self::PHASE_RUN, int $priority = 0 ): void
See
PHASE_SHUTDOWN/PHASE_EXCEPTION). If $when only names phase(s) already passed, $trigger is checked immediately instead (since executeJobs will never reach them again).
$triggercallablefunction(): bool.
$jobcallablefunction(): void.
$when = self::PHASE_RUNinta bitmask of PHASE_* constants.
$priority = 0intlower runs first among jobs registered for the same phase.
returnsvoid

addJobs($jobs)

Application.php:408
function addJobs(array $jobs): void
$jobsarraylist of [$trigger, $job, $when, $priority]-shaped argument lists, each passed to addJob.
returnsvoid

addLog($log)

Application.php:367

Write log in the log stream (if any) or add it to the pool.

function addLog(MMO\core\events\Log $log): voidCall directly when any dispatcher connected to the application dispatch a Log. WARNING: The verbosity of the application has no effect on the log being added, except when it is set to 0. In that case, ALL logs are ignored.
$logLog
returnsvoid

addRoute($groupId, $route)

Application.php:742

Add one more route to $groupId (creating the group if needed), on top of whatever connectRoutes already extracted. @return APIRoute $route, for chaining.

function addRoute(string $groupId, MMO\core\attributes\APIRoute $route): MMO\core\attributes\APIRoute
$groupIdstring
$routeAPIRoute
returnsAPIRoute

captureAutoload($capture)

Application.php:1236

Set/unset php autoload hook

function captureAutoload(bool $capture = true): self
$capture = truebool
returnsself

captureErrors($capture)

Application.php:1195

Set/unset php error hook

function captureErrors(bool $capture = true): self
$capture = truebool
returnsself

classUrl($class, $extension, $resolve)

Application.php:620

Convert a classname/namespace into an uri with an path

function classUrl( string $class, string $extension = MMO\core\PHP_EXTENSION, bool $resolve = true ): ?string
$classstring
$extension = MMO\core\PHP_EXTENSIONstringthe file extension to use (without .). Leave empty if you want to get a namespace's folder.
$resolve = trueboolif false, returned an uri containing path
returnsnull | stringnull if no path was found

clearLogs($disableLogs)

Application.php:400
function clearLogs(bool $disableLogs = false): void
$disableLogs = falseboolif true, also silences all further logging (tLogEmitter::setVerbosity(0)).
returnsvoid

connectRoutes($class, $config)

Application.php:807

Connect route of a class or a function

function connectRoutes(string $class, array $config = []): bool
$classstringa classname or a valid function's name
$config = []array
returnsbool
throws
throwsif application is already running

createErrorResponse($e)

Application.php:888

Called by the route when an exception occurs, or by the php exception handler.

function createErrorResponse(Throwable $e): MMO\core\server\ResponseIts status is the exception's code when that is an HTTP status, 500 otherwise ([`httpStatus`](https://mcp.mmoframework.fr/documentation/mmo.core/php/server.md#httpstatus)): a PDOException's code is its SQLSTATE, a string.
\MMO\app()->createErrorResponse($pdoException)->getStatusCode(); // 500

dump($values)

Application.php:218

Dump $values using whichever printer matches the current response's content type (falling back to $printer before any response exists).

function dump(mixed ...$values)
...$valuesmixed
returns

executeJobs($when)

Application.php:504

Run every job (addJob) whose trigger currently returns true and whose $when includes $when; a job throwing is logged, not propagated.

function executeJobs(int $when): void
$whenint
returnsvoid

extractRoutes($class, $config)

Application.php:769

Extract api routes from a function/class attributes

function extractRoutes(string $class, array $config = []): array
$classstringa function's name or a classname
$config = []array- basepath: the route basepath
returnsarraya sorted list of APIRoute
throws

findRoute($groupId, $operation)

Application.php:732
function findRoute(string $groupId, callable|string|null $operation = null): ?MMO\core\attributes\APIRoute
$groupIdstring
$operation = nullcallable | string | nulldefaults to $groupId itself (the common case: a group with one route, named after itself).
returnsnull | APIRoutethe route in $groupId whose operation matches, or null.

getJobs($when, $executeTrigger)

Application.php:485
function getJobs(object|int $when = -1, bool $executeTrigger = false): array
$when = -1object | inta PHASE_* bitmask, or an object instance to find jobs bound to (matches a [$instance, 'method']-style job callable whose object is === $when).
$executeTrigger = falseboolif true, only include jobs whose trigger currently returns true (and actually call each one).
returnsarrayevery matching job callable.

getLogs($flush)

Application.php:393

Get and flush the logs in the pool.

function getLogs(bool $flush = true): array
$flush = trueboolif false, don't flush the logs from the pool
returnsarray

getRequest()

Application.php:698
function getRequest(): Psr\Http\Message\ServerRequestInterface
returnsServerRequestInterfacethe current route's request, or (before handling one) a freshly-built one from the real environment (CLI argv or the real HTTP request).

getRoute()

Application.php:693
function getRoute(): ?MMO\core\server\Route
returnsnull | Routethe route currently being handled (handle), or null before any request has been handled.

getRoutes($groupId)

Application.php:706
function getRoutes(?string $groupId = null): array
$groupId = nullnull | stringif given, only that group's routes; if null, every group.
returnsarrayAPIRoute[] (or array<string, APIRoute[]> when $groupId is null).

getWorker($id, $regex)

Application.php:323
function getWorker(string $id, bool $regex = false): ?array
$idstringa pid or exact command to match, or (with $regex) a regex to match the command against.
$regex = falsebool
returnsnull | arraythe matching worker (getWorkers' shape), or null.

getWorkers()

Application.php:285
function getWorkers(): array
returnsarray[['date' => ..., 'pid' => ..., 'cmd' => ..., 'main' => the registering process's own pid, 'run' => bool whether it's still running], ...] -- every registered worker; also prunes no-longer-running ones from the registry file as a side effect (deleting the file entirely once none are left).

handle($request)

Application.php:825
function handle(Psr\Http\Message\ServerRequestInterface $request): MMO\core\interfaces\iResponse
See
RequestHandlerInterface::handle -- match $request against every registered route (connectRoutes), adding a middleware for each match (Route::addMiddleware), then Route::dispatch and Route::handle it. An uncaught exception from the route becomes an error response instead (createErrorResponse), via the route's own error handler if it set one.
$requestServerRequestInterface
returnsiResponse

hasRoutes($groupId)

Application.php:758
function hasRoutes(string $groupId): bool
$groupIdstring
returnsboolwhether $groupId has any routes registered.

phpAutoload($class)

Application.php:1142

Magic php autoload handler Use directly spl_autoload_register

function phpAutoload(string $class): void
$classstring
returnsvoid

phpError($no, $str, $file, $line, $context)

Application.php:1070

Magic php error handler Maps a raw PHP error (set_error_handler) to a log level and message, ignoring the @-suppression operator by design -- so an error a caller tried to silence via @ is still logged/recorded, just not displayed.

function phpError( int $no, string $str, ?string $file = null, ?int $line = null, mixed $context = null ): bool
$noint
$strstring
$file = nullnull | string
$line = nullnull | int
$context = nullmixed
returnsboolalways true (tells PHP not to run its own default error handler too).

phpShutdown()

Application.php:1151

Shutdown function call by register_shutdown_function WARNING: DO NOT call directly. It is called automatically by the shutdown process.

function phpShutdown(): void
returnsvoid

removeRoutes($groupId)

Application.php:749
function removeRoutes(string $groupId): bool
$groupIdstring
returnsboolfalse if $groupId wasn't registered.

resolvePath($uri, $maxRecursivity)

Application.php:599

Resolve path recursively.

function resolvePath(string $uri, int $maxRecursivity = 10): string
$uristring
$maxRecursivity = 10int
returnsstring

routeAPI($route)

Application.php:1054

API endpoint serving api's OpenAPI document; stops further middleware so nothing else can alter it.

#[MMO\core\attributes\APIRoute('GET|api.json', 'Get the OpenAPI document for the routes of the application', order: -1000, mediaTypes: ['json'])] function routeAPI(MMO\core\server\Route $route): MMO\core\server\Response
$routeRoute
returnsResponse

run($request)

Application.php:928

Run and exit the application

function run(?Psr\Http\Message\ServerRequestInterface $request = null): never
$request = nullnull | ServerRequestInterface
returnsneverit exits the script

runInteractive($request)

Application.php:918

Run the application, executing middlewares and returns a Response or an exception

function runInteractive(?Psr\Http\Message\ServerRequestInterface $request = null): ?MMO\core\interfaces\iResponse
$request = nullnull | ServerRequestInterface
returnsnull | iResponse

runWorker($cmd, $sleep)

Application.php:259

Start $cmd as a detached background process and register it (registerWorker).

function runWorker(string $cmd, int $sleep = 1): string
$cmdstring
$sleep = 1intseconds to wait before checking the process actually started.
returnsstringthe new process's PID.
throwsif the process doesn't appear to be running after $sleep seconds (already running under this exact command, per getWorker, is reported specifically; anything else is a generic failure).

sendResponse($response)

Application.php:947

Call this function to send a response

function sendResponse(MMO\core\interfaces\iResponse $response): bool
$responseiResponse
returnsboolfalse if the response's own dispatch stopped propagation (nothing was sent), or if sending itself failed (logged as critical, not thrown).
throwsif a response has already been sent (getResponse).

setIncludes($pkgs)

Application.php:234

Include packages after the project and the application has been instantiated

function setIncludes(array $pkgs): void
$pkgsarrayinc
returnsvoid

setPath($path, $value)

Application.php:565

Set a path for an uri part A path xxx replace any uri parts named {xxx}

function setPath(string $path, string $value): bool
$pathstringthe path's name without curly brackets.
$valuestring
returnsbool

setPaths($paths, $isWindows)

Application.php:585

Set path for given paths.

function setPaths(array $paths, bool $isWindows = MMO\core\IS_WINDOWS): voidOn Windows, convert `\` to `/` in path. On linux same as `setPath($path, $path)`
$pathsarray$name => $path ($name is the path's name without curly brackets).
$isWindows = MMO\core\IS_WINDOWSbool
returnsvoid

setStream($stream)

Application.php:339

Set the stream to write the logs in

function setStream(Psr\Http\Message\StreamInterface|string|null $stream = null): bool
$stream = nullStreamInterface | string | null
returnsbool
Inherited members (46)
ConstantsDeclared byDescription
ALERTiLogLevelAlert: Action must be taken immediately.
ALLiLogLevelMask for all
ALL_PLUSiLogLeveldebug everything
BACKTRACEiLogLevel
CRITICALiLogLevelCritical: Critical conditions.
DEBUGiLogLevelDebug: Detailed debug information.
DEEPiLogLeveldebug everything with arguments
EMERGENCYiLogLevelEmergency: System is unusable.
ERRORiLogLevelError: Runtime errors that do not require immediate action but should typically be logged and monitored.
ERROR_PLUSiLogLevelMask for all error
FATALiLogLevelMask for all fatal error
INFOiLogLevelInfo: Interesting events.
INFO_PLUSiLogLevelMask for all errors/warning/notices/info
MEMORYiLogLevelinclude backtrace object
NOTICEiLogLevelNotice: Normal but significant events.
NOTICE_PLUSiLogLevelMask for all errors/warning/notices/info
TRACEiLogLevelinclude backtrace as origins
WARNINGiLogLevelWarning: Exceptional occurrences that are not errors.
WARNING_PLUSiLogLevelMask for all errors and warnings
PropertiesDeclared byDescription
verbosityaModule
MethodsDeclared byDescription
alert($message, $context)aModuleAction must be taken immediately.
backtraces($message, $context)aModuleForce-log a message at INFO level together with a full stack trace/memory snapshot (iLogLevel::BACKTRACE), bypassing the verbosity mask entirely (any non-zero verbosity is enough to trigger it).
Configure($config)aModuleMerge $config into this module's configuration in the shared Configuration.
critical($message, $context)aModuleCritical conditions. No-op if CRITICAL is currently filtered out by the verbosity mask.
debug($message, $context)aModuleDetailed debug information.
debugName()aModuleHuman-readable identifier used as the default {origin} in this instance's log messages.
emergency($message, $context)aModuleSystem is unusable. No-op if EMERGENCY is currently filtered out by the verbosity mask.
error($message, $context)aModuleRuntime errors that do not require immediate action but should typically be logged and monitored.
getVerbosity()aModule
info($message, $context)aModuleInteresting events. No-op if INFO is currently filtered out by the verbosity mask.
Instantiate($config)aModule(Re)create the shared instance immediately, configured with $config merged into the class's existing config.
IsShared()aModule
log($level, $message, $context)aModuleLogs with an arbitrary level.
notice($message, $context)aModuleNormal but significant events.
offsetExists($key)aModule\ArrayAccess::offsetExists -- tells whether $key is a declared property at all, regardless of whether it is currently readable/writable through array access.
offsetGet($key)aModule\ArrayAccess::offsetGet -- reads a property directly, unless it has a #[Serialize(serialize: 'methodName')] attribute, in which case that zero-argument method is called instead (e.g.
offsetSet($key, $value)aModule\ArrayAccess::offsetSet -- sets a property directly, unless it has a #[Serialize(unserialize: 'methodName')] attribute, in which case that method is called with $value instead (e.g.
offsetUnset($key)aModule\ArrayAccess::offsetUnset -- equivalent to $module[$key] = null.
serialize($path, $serializer)aModule\MMO\core\interfaces\iSerializable::serialize -- exports every property (via
setVerbosity($verb)aModuleSet the current verbosity mask, replacing whatever it was before.
Shared()aModuleGet the shared instance, creating (and configuring) it on first call.
testVerbosity($level)aModuleTest whether a given level (or set of levels) is currently enabled by this instance's verbosity mask.
traitUnshare($serialize)aModuleRemove the shared instance, so the next Shared() call creates a fresh one.
unserialize($data, $path, $instances)aModule\MMO\core\interfaces\iSerializable::unserialize -- merges $data onto DefaultConfig, runs it through the (possibly overridden) constructor, then applies each resulting value to its property (via
Unshare($serialize)aModuleLike tSingleton::Unshare, but also disconnects this module's instance from every event it was listening to (via Event::DisconnectListeners) before dropping it.
warning($message, $context)aModuleExceptional occurrences that are not errors.