Skip to content

Developer Guide Events and Objects

Stefan Crkvenjakov edited this page Oct 7, 2026 · 1 revision

Events, shared objects and object creation

Developer Guide · Runtimes

Internals: Events and Context, Objects, Runtime, EventDispatcher.

Communicate through events

An event implements IEvent with getName(): string and bundle(): array. A listener implements IEventListener with handle(IEvent $event): array. Registration is explicit and synchronous; events do not discover listeners automatically or run background jobs.

Complete MessageHub/events/MessageCreated.php:

<?php
namespace MessageHub\events;

use event\interfaces\IEvent;

final class MessageCreated implements IEvent
{
    public function __construct(public readonly int $messageId) {}
    public function getName(): string { return 'demo.message.created'; }
    public function bundle(): array { return ['messageId' => $this->messageId]; }
}

Complete Reports/listeners/MessageCounter.php:

<?php
namespace Reports\listeners;

use event\interfaces\IEvent;
use event\interfaces\IEventListener;

final class MessageCounter implements IEventListener
{
    public function handle(IEvent $event): array
    {
        $id = $event->bundle()['messageId'];
        return ['received' => $id];
    }
}

In Reports' runtime setup(), assuming an installed Reports package with this class:

$this->eventDispatcher->addListener(
    'demo.message.created', new \Reports\listeners\MessageCounter()
);

In a later MessageHub controller/action or runtime main():

$results = $this->eventDispatcher->dispatch(
    new \MessageHub\events\MessageCreated(42)
);

The listener must be registered before dispatch. For a startup-time event, use an appropriate manifest dependency/runtime wait to order registration; for a request-time event all package startup has already occurred. Results are an array of listener result arrays, e.g. [['received' => 42]]. An event with no listeners returns []. Exceptions stop dispatch and propagate. removeListeners($eventName) removes all listeners for that name, not one listener. Use unique event names and leave reserved context events to the framework.

Choose the right sharing mechanism

Mechanism What it provides Scope and ownership
Resource A resolved package file path or generated public resource URL Package-owned filesystem content, looked up through VFS. It is not an object registry.
Shared value/object A named value published by setShared()/addShared() Request-wide registry under publishing package name. Values can be scalars, arrays or object references. No cross-request persistence is implied.
Passable runtime An executed API object retained with CreatePassable Request-wide registry under package name and actual runtime class name. Use it to access controllers or other runtime capabilities.
ObjectFactory A recipe for creating/configuring an object Each create() normally makes a new instance; a route replaces its factory with the resulting controller for that route.
ObjectHandler/getLocalObject A zero-argument concrete object loaded from a file Creates an object; it is not a service container or singleton registry.

Place $this->waitForPackage('MessageHub') in the consuming runtime's environmentSetup(). After that wait resolves, retrieve the shared object in setup():

$metrics = $this->getShared('MessageHub', 'metrics', \ArrayObject::class);
if (!$metrics instanceof \ArrayObject) {
    throw new \LogicException('MessageHub did not publish metrics.');
}
$metrics['messages']++;
$this->setShared('metrics', $metrics);

The last call publishes the same object under the consuming package's own name. The original shared object also observes the mutation because it is the same PHP object. getShared() returns null for a missing value; when a nonnull value fails expectedType, it throws RuntimeException. addShared(name, object) is an object-only alias for setShared(name, mixed). setSharable(array) replaces the whole runtime shared registry; use ordinary setShared() for incremental publication.

Passable retrieval excerpts inside a runtime:

$local = $this->getPassable(\DemoSite\components\PageControllers::class);
$remote = $this->getPassable(
    'DemoSite', \DemoSite\components\PageControllers::class,
    \runtime\api\RuntimeControllerAPI::class
);

One argument selects a class within the current package. Two select package/class. An optional type mismatch returns null rather than throwing. A runtime appears only after its main() returns and CreatePassable is processed. Runtime base classes do not expose a supported $this->shared array despite an older enum comment; use the methods above. Controller/Router shared properties exist but are not automatically populated from the runtime registry.

Factories and collections

ObjectFactory supports setClassName(), setClassPath(), setType(), setConstructorArgs(), setProperties(), setMethodCalls() and setMethodArgs(). Creation order is constructor → type check → property assignments → method calls in configured order. Use setProperties() for object/mixed values; addProperty() currently accepts a string. Missing properties/methods or wrong type produce exceptions in DEBUG mode and may be skipped/null in nondebug mode. Visibility still matters: a declared private property cannot be assigned directly just because property_exists() succeeds.

ObjectHandler selects the first concrete class actually declared by a file, even if the include autoloaded other classes. Put one runtime or hook class per file. Constructors that need arguments require ObjectFactory's constructor configuration; getLocalObject(relativePath) cannot pass them.

ObjectCollection accepts objects, optionally enforces a type, and provides setKey(), setOrder(), setSortProperties(), setValueOrder(), add(), sortByKey(), sortByValue(), find() and toArray(). Unsorted find() uses its key as a collection index, ignoring the value; sorted find() performs a binary search and needs the searched key to match the sort order. Use public sortable properties. setPropertyAccessor(callable) exists but its backing field is ?string, so Closure accessors currently raise TypeError; see discrepancies.

Package context

Inside a controller, getContext() returns the context injected by the controller API. Elsewhere dispatch GetContextEvent, then getContext() on that event after a responder handles it. Calling before dispatch/no responder leaves its typed context uninitialized. Context provides contextPath, contextName and string contextId. Context switching is request execution state; do not cache “current package” indefinitely in a global object.

Clone this wiki locally