Skip to content

Phalcon events

NOTE

All classes are prefixed with Phalcon

Events\AbstractEventsAware

Abstract Source on GitHub

This abstract class offers access to the events manager

Uses Phalcon\Events\ManagerInterface

Method Summary

Properties

protected ManagerInterface|null $eventsManager = null

Methods

Public · 2

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

Protected · 1

fireManagerEvent()

protected function fireManagerEvent(
    string $eventName,
    mixed $data = null,
    bool $cancellable = true
): mixed|bool;

Helper method to fire an event

Events\Event

Class Source on GitHub

This class offers contextual information of a fired event in the EventsManager

Phalcon\Events\Event;

$event = new Event("db:afterQuery", $this, ["data" => "mydata"], true);
if ($event->isCancelable()) {
    $event->stop();
}

Uses Phalcon\Contracts\Events\Stoppable · Phalcon\Events\Exceptions\EventNotCancelable · Phalcon\Events\Exceptions\InvalidEventSource

Method Summary

Properties

protected bool $cancelable Is event cancelable?
protected mixed $data Event data
protected object|null $source = null Event source
protected bool $stopped = false Is event propagation stopped?
protected string $type Event type

Methods

Public · 10

__construct()

public function __construct(
    string $type,
    mixed $source = null,
    mixed $data = null,
    bool $cancelable = true
);

Phalcon\Events\Event constructor

getData()

public function getData(): mixed;

getSource()

public function getSource(): object|null;

getType()

public function getType(): string;

isCancelable()

public function isCancelable(): bool;

Check whether the event is cancelable.

if ($event->isCancelable()) {
    $event->stop();
}

isPropagationStopped()

public function isPropagationStopped(): bool;

Returns whether propagation must stop. PSR-14 alias backed by the same stopped flag as isStopped(); calling stop() flips both.

isStopped()

public function isStopped(): bool;

Check whether the event is currently stopped.

setData()

public function setData( mixed $data = null ): EventInterface;

Sets event data.

setType()

public function setType( string $type ): EventInterface;

Sets event type.

stop()

public function stop(): EventInterface;

Stops the event preventing propagation.

if ($event->isCancelable()) {
    $event->stop();
}

Events\EventInterface

Interface Source on GitHub

Phalcon\Events\EventInterface

Uses Phalcon\Contracts\Events\Event

Events\EventsAwareInterface

Interface Source on GitHub

Phalcon\Events\EventsAwareInterface

Uses Phalcon\Contracts\Events\EventsAware

Events\Exception

Class Source on GitHub

Exceptions thrown in Phalcon\Events will use this class

Events\Exceptions\EventNotCancelable

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Events\Exceptions\InvalidEventHandler

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Events\Exceptions\InvalidEventSource

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $type,
    string $sourceType
);

Events\Exceptions\InvalidEventType

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $eventType );

Events\Exceptions\InvalidSubscriberConfiguration

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $eventName );

Events\Exceptions\NoListenersForEvent

Class Source on GitHub

Uses Phalcon\Events\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $eventType );

Events\Manager

Class Source on GitHub

Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, the normal flow of operation. With the EventsManager the developer can create hooks or plugins that will offer monitoring of data, manipulation, conditional execution and much more.

Uses Closure · Phalcon\Contracts\Events\Stoppable · Phalcon\Contracts\Events\Subscriber · Phalcon\Events\Exceptions\InvalidEventHandler · Phalcon\Events\Exceptions\InvalidEventType · Phalcon\Events\Exceptions\InvalidSubscriberConfiguration · Phalcon\Events\Exceptions\NoListenersForEvent

Method Summary

public void addSubscriber( Subscriber $subscriber ) Registers an event subscriber. The subscriber's getSubscribedEvents() public bool arePrioritiesEnabled() Returns if priorities are enabled public void attach(string $eventType,mixed $handler,int $priority = self::DEFAULT_PRIORITY) Attach a listener to the events manager public void clearSubscribers() Removes every registered subscriber and detaches each listener they public void collectResponses( bool $collect ) Tells the event manager if it needs to collect all the responses returned public void detach(string $eventType,mixed $handler) Detach the listener from the events manager public void detachAll( string $type = null ) Removes all events from the EventsManager public dispatch(object $event,mixed $name = null,mixed $source = null) Dispatches an object event to its listeners, routed by an explicit name public void enablePriorities( bool $enablePriorities ) Set if priorities are enabled in the EventsManager. public fire(string $eventType,object $source,mixed $data = null,bool $cancelable = true) Fires an event in the events manager causing the active listeners to be public array fireAll(string $eventType,object $source,mixed $data = null,bool $cancelable = true) Fires an event and returns every listener's return value as an public fireQueue(array $queue,EventInterface $event) Internal handler to call a queue of events. public array getListeners( string $type ) Returns all the attached listeners of a certain type public int getMethodExistsCacheLimit() Returns the configured method_exists-cache cap (0 = unlimited). public array getResponses() Returns all the responses returned by every handler executed by the last public array getSubscribers() Returns the list of registered subscriber instances. Useful for public void halt() Manager-level kill switch. After halt(), every fire()/fireAll()/ public bool hasListeners( string $type ) Check whether certain type of event has listeners public bool isCollecting() Check if the events manager is collecting all all the responses returned public bool isHalted() Returns whether the manager-level kill switch is engaged. See halt(). public bool isStopOnFalse() Returns whether the stop-on-false short-circuit is enabled. public bool isStrict() Returns whether strict mode is enabled. When true, fire()/fireAll() public bool isValidHandler( mixed $handler ) public void removeSubscriber( Subscriber $subscriber ) Removes a previously registered subscriber. Detaches every listener the public void resume() Clears the manager-level kill switch set by halt(). Subsequent public void setMethodExistsCacheLimit( int $methodExistsCacheLimit ) Caps the number of distinct handler classes retained in the public void setStopOnFalse( bool $flag ) Enables/disables the stop-on-false short-circuit. When true, a public void setStrict( bool $strict ) Enables/disables strict mode. When true, fire()/fireAll() throw protected mixed afterFire(mixed $status,string $eventType,object $source,mixed $data = null,bool $cancelable = true) Extension seam invoked after an event has been dispatched to its protected bool beforeFire(string $eventType,object $source,mixed $data = null,bool $cancelable = true) Extension seam invoked before an event is dispatched. The base

Properties

protected bool $collect = false
protected bool $enablePriorities = false
protected array $eventNameCache = [] Parsed-eventType cache. Memoizes the strpos + substr work done in fire() so the same event name fired repeatedly (the common case for db:beforeQuery, model:afterSave, etc.) collapses to a single hash lookup. Shape: eventNameCache[$eventType] = [typePrefix, eventName] Unbounded by design - distinct event types in a typical Phalcon application are well under 100 keys, and the cache never needs invalidation (parse is deterministic for a given eventType string).
protected array $events = [] Listener storage. Shape: events[$eventType] = [ [handler, type, priority] // types 0, 1, 3 [handler, type, priority, className] // type 2 carries // resolved class name ... ] Kept sorted by priority descending when priorities are enabled (FIFO within the same priority); otherwise listeners are simply appended in attach order. type is classified once at attach() time so dispatch() can route via a simple branch: 0 - Closure: direct invocation via {handler}(args), no arg-array alloc per call 1 - [obj, method] array callable: direct dynamic dispatch handler[0]->{handler[1]}(args) 2 - plain object: dynamic dispatch via method named after the event (the classic Phalcon listener pattern); class name is captured at attach time to skip get_class() per fire 3 - generic callable (string fn name, invokable object, [class, staticMethod]): call_user_func_array
protected int $fireDepth = 0 Re-entrancy depth of fire()/fireAll(). 0 means no fire is in progress. Incremented on every fire entry, decremented on exit. Used to keep nested fire() calls from clobbering the outer caller's $this->responses accumulator.
protected bool $halted = false Manager-level kill switch. When true, every fire()/fireAll()/ fireQueue() call returns immediately (null or empty array) without dispatching. Cleared by resume(). Survives across fire() calls, unlike Event::stop() which only stops the current dispatch chain.
protected array $methodExistsCache = [] Memoized method_exists() results for the OBJECT_METHOD dispatch path in dispatch(). Keyed by handlerClass => [methodName => bool]. A class doesn't gain methods at runtime so the lookup is permanent.
protected int $methodExistsCacheLimit = 0 Maximum number of distinct handler classes retained in methodExistsCache. 0 (default) keeps the original unbounded behavior; a positive value clears the cache when adding a new class would exceed it. Re-warming is cheap (method_exists is O(1)) and the cap is meant for very long-lived workers that see many distinct listener classes over time.
protected array $responses = []
protected bool $stopOnFalse = false When true, a listener returning literal false (with the event's cancelable flag on) short-circuits the dispatch loop and pins the fire() return as false. Default off - preserves the pre-5.13 "last-wins" contract for codebases that rely on later listeners overriding an earlier false return [#17019].
protected bool $strict = false When true, fire()/fireAll() throw on dispatch of an event that has zero matching listeners. Catches typos in dev. Default off.
protected array $subscriberEventsCache = [] Memoized getSubscribedEvents() maps keyed by Subscriber class name. The static method's return is stable for the lifetime of a class definition, so the cache never needs invalidation.
protected array $subscribers = []

Methods

Public · 28

addSubscriber()

public function addSubscriber( Subscriber $subscriber ): void;

Registers an event subscriber. The subscriber's getSubscribedEvents() map is parsed and each entry is attached through the regular listener pipeline.

arePrioritiesEnabled()

public function arePrioritiesEnabled(): bool;

Returns if priorities are enabled

attach()

final public function attach(
    string $eventType,
    mixed $handler,
    int $priority = self::DEFAULT_PRIORITY
): void;

Attach a listener to the events manager

clearSubscribers()

public function clearSubscribers(): void;

Removes every registered subscriber and detaches each listener they contributed. Listeners attached via attach() are untouched.

Iterates a snapshot of subscribers so removeSubscriber() can safely mutate the original property during the walk.

collectResponses()

public function collectResponses( bool $collect ): void;

Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire

detach()

public function detach(
    string $eventType,
    mixed $handler
): void;

Detach the listener from the events manager

detachAll()

public function detachAll( string $type = null ): void;

Removes all events from the EventsManager

dispatch()

public function dispatch(
    object $event,
    mixed $name = null,
    mixed $source = null
);

Dispatches an object event to its listeners, routed by an explicit name (a string, or a [class, method] array) or, failing that, by the event's class name. Listeners receive the event object. Propagation stops when the event implements Phalcon\Contracts\Events\Stoppable and reports it is stopped.

enablePriorities()

public function enablePriorities( bool $enablePriorities ): void;

Set if priorities are enabled in the EventsManager.

A priority queue of events is a data structure similar to a regular queue of events: we can also put and extract elements from it. The difference is that each element in a priority queue is associated with a value called priority. This value is used to order elements of a queue: elements with higher priority are retrieved before the elements with lower priority.

fire()

public function fire(
    string $eventType,
    object $source,
    mixed $data = null,
    bool $cancelable = true
);

Fires an event in the events manager causing the active listeners to be notified about it

$eventsManager->fire("db", $connection);

fireAll()

public function fireAll(
    string $eventType,
    object $source,
    mixed $data = null,
    bool $cancelable = true
): array;

Fires an event and returns every listener's return value as an indexed array. Independent of collectResponses(); the caller's collected state on $this->responses is preserved (stashed and restored across the call).

$results = $eventsManager->fireAll("db:beforeQuery", $connection);

fireQueue()

final public function fireQueue(
    array $queue,
    EventInterface $event
);

Internal handler to call a queue of events.

Kept at its original 2-arg signature for BC; thin wrapper around the private dispatch() helper. Direct callers pay the cost of re-extracting metadata from the Event; the framework's own fire() path bypasses this wrapper and calls dispatch() with hoisted args.

getListeners()

public function getListeners( string $type ): array;

Returns all the attached listeners of a certain type

getMethodExistsCacheLimit()

public function getMethodExistsCacheLimit(): int;

Returns the configured method_exists-cache cap (0 = unlimited). See setMethodExistsCacheLimit().

getResponses()

public function getResponses(): array;

Returns all the responses returned by every handler executed by the last 'fire' executed

getSubscribers()

public function getSubscribers(): array;

Returns the list of registered subscriber instances. Useful for introspection and test setup/teardown.

halt()

public function halt(): void;

Manager-level kill switch. After halt(), every fire()/fireAll()/ fireQueue() call returns immediately without dispatching, until resume() is called. Use this when a listener needs to abort all subsequent event activity for the lifetime of the manager (e.g. a security check that cancels everything downstream).

hasListeners()

public function hasListeners( string $type ): bool;

Check whether certain type of event has listeners

isCollecting()

public function isCollecting(): bool;

Check if the events manager is collecting all all the responses returned by every registered listener in a single fire

isHalted()

public function isHalted(): bool;

Returns whether the manager-level kill switch is engaged. See halt().

isStopOnFalse()

public function isStopOnFalse(): bool;

Returns whether the stop-on-false short-circuit is enabled. See setStopOnFalse().

isStrict()

public function isStrict(): bool;

Returns whether strict mode is enabled. When true, fire()/fireAll() throw when an event has no matching listeners - useful in dev to catch typos. Default off.

isValidHandler()

public function isValidHandler( mixed $handler ): bool;

removeSubscriber()

public function removeSubscriber( Subscriber $subscriber ): void;

Removes a previously registered subscriber. Detaches every listener the subscriber declared via getSubscribedEvents(). Idempotent - calling with a subscriber that was never added (or already removed) is a no-op.

resume()

public function resume(): void;

Clears the manager-level kill switch set by halt(). Subsequent fire()/fireAll()/fireQueue() calls resume normal dispatch.

setMethodExistsCacheLimit()

public function setMethodExistsCacheLimit( int $methodExistsCacheLimit ): void;

Caps the number of distinct handler classes retained in the method_exists memoization cache. 0 disables the cap (the default; preserves the original unbounded behavior). When the cap is exceeded, the cache is cleared and re-warms on subsequent fires.

setStopOnFalse()

public function setStopOnFalse( bool $flag ): void;

Enables/disables the stop-on-false short-circuit. When true, a listener returning literal false (with cancelable=true) stops the current event's queue and pins the fire() return as false. Later listeners cannot overwrite the cancel. Default off.

Independent of halt() / event->stop() - only governs how the dispatch loop reacts to a false listener return.

setStrict()

public function setStrict( bool $strict ): void;

Enables/disables strict mode. When true, fire()/fireAll() throw when dispatching an event with zero matching listeners.

Protected · 2

afterFire()

protected function afterFire(
    mixed $status,
    string $eventType,
    object $source,
    mixed $data = null,
    bool $cancelable = true
): mixed;

Extension seam invoked after an event has been dispatched to its listener queues. Receives the computed dispatch result as status and returns the value fire() hands back to its caller; the base implementation returns status unchanged. A subclass can override it to run bookkeeping or to post-process / rewrite the result.

Only called when the event was actually dispatched; the halted and no-listener short-circuits in fire() return before reaching it.

beforeFire()

protected function beforeFire(
    string $eventType,
    object $source,
    mixed $data = null,
    bool $cancelable = true
): bool;

Extension seam invoked before an event is dispatched. The base implementation returns true, so dispatch proceeds unchanged. A subclass can override it to inspect the source and data and, by returning false, abort the dispatch entirely - for example to redirect a deferred event onto an external queue. Invoked before the no-listener short-circuits, so it sees every fire(), including those with no locally attached listeners.

Events\ManagerInterface

Interface Source on GitHub

Phalcon\Events\ManagerInterface

Uses Phalcon\Contracts\Events\Manager