Search by

presentkim / session-utils

PresentKim

General-purpose player session management library for axolotl-pm/PocketMine-MP

Package info

github.com/presentkim-pm/session-utils

pkg:composer/presentkim/session-utils

Statistics

Installs: 68

Dependents: 0

Suggesters: 0

Stars: 3

Open Issues: 0

3.0.0 2026-12-03 10:27 UTC

This package is auto-updated.

Last update: 2026-12-03 10:28:30 UTC


README

Packagist CI Stars License


Logo

session-utils

Per-player sessions for PocketMine-MP, created, routed and cleaned up for you.

Packagist · Changelog · Report a bug · Request a feature

한국어 README

final class CombatSession extends Session implements LifecycleSession{
    protected function onStart() : void{ /* player joined */ }
    protected function onTerminate(string $reason) : void{ /* player left, plugin disabled, ... */ }

    #[SessionEventHandler(EntityDamageByEntityEvent::class)]
    public function onHit(EntityDamageByEntityEvent $event) : void{ /* only for this player's session */ }
}

new SessionManager($this, CombatSession::class); // that is all the wiring

🌟 Why session-utils?

Almost every plugin keeps some state per player: a selection, a minigame state, a tutorial step, a cooldown. That means a PlayerJoinEvent / PlayerQuitEvent listener, an array keyed by player, event listeners that look the player up and ignore everyone else, and cleanup when the plugin is disabled. This library does it once, correctly:

  • No listener classes : mark a method with #[SessionEventHandler] and it only runs for the player who owns the session
  • Automatic lifecycle : lifecycle sessions are created on join (and for players already online) and terminated on quit
  • Safe shutdown : the manager closes itself when its plugin is disabled, no onDisable() code needed
  • Multi-step flows : SessionSequence chains sessions for tutorials, quests and wizards
  • One PMMP listener per event : many session types listening to the same event share a single registered listener
  • Predictable termination : onTerminate() first, then the onSessionTerminated callback, each exactly once
  • Failures stay contained : an exception in onStart(), onTerminate() or a callback is logged, never thrown into the server
  • Light state too : PlayerMap and Cooldown for a single value or cooldown per player, cleaned up for you
  • Tested : run against the real server code on PHP 8.4 / 8.5

🎯 Use cases

You are building... Use
Per-player stats, combat tags, scoreboards A lifecycle session (LifecycleSession)
Region selection, build tools, edit modes A task session with createSession() / removeSession()
Tutorials, quests, onboarding SessionSequence
Confirmation prompts, chat input flows A task session that terminates itself when done
One value per player, use cooldowns PlayerMap, Cooldown

📦 Installation

composer require presentkim/session-utils
Requirement Version
Server axolotl-pm/PocketMine-MP (fork of PocketMine-MP 5)
PHP 8.4 or newer

session-utils is a Composer library, not a plugin. When you build your plugin for release, shade it (give its namespace a unique prefix) and pack it into the plugin .phar together with vendor/. Every plugin then carries its own copy, so two plugins can use different versions of the library without clashing.

composer.json requires pocketmine/pocketmine-mp because that is the package name plugin projects depend on for the PocketMine-MP API. The axolotl-pm fork is only a dev dependency, used for the tests and the static analysis in this repository.

The Poggit virion for the original PocketMine-MP 5.44 and older is kept on the legacy/pmmp-5.44 branch (no longer maintained).

🧠 Concepts

Lifecycle session Task session
Interface LifecycleSession (none)
Created Automatically on PlayerJoinEvent, and when the manager is constructed for players already online Manually via createSession()
Ended Automatically on PlayerQuitEvent Manually via removeSession() or terminate()
Use case Per-player persistent state On-demand feature sessions
  • A SessionManager handles exactly one session class. Create one manager per session type.
  • A session belongs to one player and is active between its start and terminate(). The manager starts it; plugin code never calls Session::start(). Calling terminate() inside a session removes it from its manager. A terminated session cannot be started again.
  • A lifecycle session is created by the manager with only the manager and the player, so its constructor must not require extra arguments. Task sessions may take extra arguments through createSession().
  • A player who is already disconnected gets no session, and PlayerMap ignores such players too.
  • Sessions of a SessionSequence extend SequenceSession and are not lifecycle sessions.
  • A manager closes itself when its owning plugin is disabled (all sessions are terminated with PLUGIN_DISABLE and all listeners are detached). A closed manager throws LogicException from createSession() and getOrCreateSession().

🚀 Quick start

1. Define a lifecycle session

Extend Session and implement LifecycleSession for automatic join/quit management. Declare event handlers with #[SessionEventHandler]: no separate listener class needed.

use pocketmine\event\block\BlockBreakEvent;
use pocketmine\event\player\PlayerInteractEvent;
use kim\present\utils\session\Session;
use kim\present\utils\session\LifecycleSession;
use kim\present\utils\session\listener\attribute\SessionEventHandler;

final class WorldEditSession extends Session implements LifecycleSession{

    /** @var array{float, float, float}|null */
    private ?array $pos1 = null;
    /** @var array{float, float, float}|null */
    private ?array $pos2 = null;

    protected function onStart() : void{
        $this->getPlayer()->sendMessage("WorldEdit session started.");
    }

    protected function onTerminate(string $reason) : void{
        // save state, clean up, etc.
    }

    // Breaking a block (left click) selects the first position
    #[SessionEventHandler(BlockBreakEvent::class)]
    public function onBlockBreak(BlockBreakEvent $event) : void{
        $pos = $event->getBlock()->getPosition();
        $this->pos1 = [$pos->x, $pos->y, $pos->z];
        $event->cancel();
    }

    // Right-clicking a block selects the second position
    #[SessionEventHandler(PlayerInteractEvent::class)]
    public function onInteract(PlayerInteractEvent $event) : void{
        if($event->getAction() !== PlayerInteractEvent::RIGHT_CLICK_BLOCK){
            return;
        }
        $pos = $event->getBlock()->getPosition();
        $this->pos2 = [$pos->x, $pos->y, $pos->z];

        if($this->pos1 !== null){
            $this->getPlayer()->sendMessage("Region selected.");
            // Reset the state for the next selection. A lifecycle session must not terminate itself:
            // it would be gone until the player reconnects.
            $this->pos1 = null;
            $this->pos2 = null;
        }
    }
}

Which session receives an event

A handler runs only for the session of the event's owner: the player returned by the event's getPlayer(), or, if the event has no such method, by its getEntity() when that entity is a Player. So EntityDamageByEntityEvent goes to the session of the victim (the damaged entity), not the attacker. To react for the attacker, look the attacker's session up from the victim's handler:

#[SessionEventHandler(EntityDamageByEntityEvent::class)]
public function onDamaged(EntityDamageByEntityEvent $event) : void{
    $attacker = $event->getDamager();
    if($attacker instanceof Player){
        $attackerSession = $this->sessionManager->getSession($attacker); // ?CombatSession
    }
}

An event class with neither method (for example WorldLoadEvent) cannot be routed to a session. A handler for it is skipped with a warning in the plugin log when the manager is created.

Like PocketMine-MP's own handleCancelled, cancelled events are skipped by default (handleCancelled: false). Pass handleCancelled: true to receive them too.

2. Bootstrap from your plugin

use pocketmine\plugin\PluginBase;
use kim\present\utils\session\SessionManager;

final class MyPlugin extends PluginBase{
    /** @var SessionManager<MyPlugin, WorldEditSession> */
    private SessionManager $sessionManager;

    protected function onEnable() : void{
        $this->sessionManager = new SessionManager($this, WorldEditSession::class);

        $this->sessionManager
            ->onSessionCreated(function(WorldEditSession $session) : void{
                // e.g. log session start
            })
            ->onSessionTerminated(function(WorldEditSession $session, string $reason) : void{
                // e.g. persist state to DB
            });
    }

    // No onDisable() needed: the manager closes itself when MyPlugin is disabled,
    // terminating every session with SessionTerminateReasons::PLUGIN_DISABLE.
}

That is the whole setup. Every player who joins gets a WorldEditSession, and so do the players already online when new SessionManager(...) runs (for example after a late enable).

onSessionCreated() and onSessionTerminated() each hold a single callback: registering again replaces the previous one. onSessionCreated() also runs right away for every session that already exists, so the callback above sees the players who were online before it was registered.

3. Manage sessions manually

use kim\present\utils\session\SessionTerminateReasons;

// Create a session on demand (for non-lifecycle sessions); extra arguments go to the session constructor
$session = $this->sessionManager->createSession($player);

// Retrieve a session (returns null if none exists)
$session = $this->sessionManager->getSession($player);

// Retrieve a session or throw RuntimeException if none exists
$session = $this->sessionManager->getSessionOrThrow($player);

// Retrieve a session or create one if none exists
$session = $this->sessionManager->getOrCreateSession($player);

// All active sessions
$sessions = $this->sessionManager->getAllSessions(); // list<WorldEditSession>

// The plugin that owns the manager
$plugin = $this->sessionManager->getPlugin(); // MyPlugin

// Remove a session by session, player or runtime id (a player without a session is ignored)
$this->sessionManager->removeSession($player, SessionTerminateReasons::MANUAL);
$this->sessionManager->removeSession($session);
$this->sessionManager->removeSession($player->getId());

// Terminate every session and keep using the manager
$count = $this->sessionManager->terminateAll(SessionTerminateReasons::MAINTENANCE);

// Close the manager early (also done automatically when the plugin is disabled)
$this->sessionManager->close();
$this->sessionManager->isClosed(); // true; createSession() now throws LogicException

createSession() returns the existing session if the player already has one. It returns null, without calling onSessionCreated, when the player is no longer connected, when the session throws while it is created or started (the error is logged and the session is terminated with START_FAILED), or when the session terminated itself in onStart().

4. Define a sequence session

For multi-step flows (e.g. tutorials), extend SequenceSession and call next() to advance to the next step. The next step does not receive the event that made you call next().

use pocketmine\event\block\BlockBreakEvent;
use pocketmine\event\block\BlockPlaceEvent;
use kim\present\utils\session\sequence\SequenceSession;
use kim\present\utils\session\listener\attribute\SessionEventHandler;

final class TutorialStep1Session extends SequenceSession{

    protected function onStart() : void{
        $this->getPlayer()->sendMessage("Step 1: Break a block.");
    }

    protected function onTerminate(string $reason) : void{}

    #[SessionEventHandler(BlockBreakEvent::class)]
    public function onBlockBreak(BlockBreakEvent $event) : void{
        $this->getPlayer()->sendMessage("Step 1 complete!");
        $this->next(); // Advances to TutorialStep2Session
    }
}

final class TutorialStep2Session extends SequenceSession{

    protected function onStart() : void{
        $this->getPlayer()->sendMessage("Step 2: Place a block.");
    }

    protected function onTerminate(string $reason) : void{}

    #[SessionEventHandler(BlockPlaceEvent::class)]
    public function onBlockPlace(BlockPlaceEvent $event) : void{
        $this->getPlayer()->sendMessage("Step 2 complete!");
        $this->next(); // No next step: triggers the onComplete callback
    }
}

5. Bootstrap a sequence

use pocketmine\plugin\PluginBase;
use pocketmine\player\Player;
use kim\present\utils\session\sequence\SessionSequence;

final class MyPlugin extends PluginBase{
    private SessionSequence $tutorialSequence;

    protected function onEnable() : void{
        $this->tutorialSequence = new SessionSequence($this,
            TutorialStep1Session::class,
            TutorialStep2Session::class,
        );

        $this->tutorialSequence->onComplete(function(Player $player) : void{
            $player->sendMessage("Tutorial complete!");
            $this->saveProgress($player, completed: true);
        });
    }

    public function startTutorial(Player $player) : void{
        $progress = $this->loadProgress($player); // e.g. 0, 1

        if($progress === 0){
            $session = $this->tutorialSequence->start($player);
        }else{
            // Resume from where the player left off (by index or class-string)
            $session = $this->tutorialSequence->startFrom($player, $progress);
        }

        if($session === null){
            // The step could not be started (player disconnected or the error was logged)
        }
    }

    public function whereIsPlayer(Player $player) : ?int{
        return $this->tutorialSequence->getCurrentStep($player); // 0-based step index, or null
    }
}

start() and startFrom() first terminate the player's session in any other step with RESTART, so a player is never in two steps at once. They return the session of that step, or null if it could not be started. Like a manager, a sequence closes itself when the plugin is disabled.

Small per-player state: PlayerMap and Cooldown

Not every piece of player state needs a session class. For a single value or a cooldown, use the light entry points:

use pocketmine\math\Vector3;
use pocketmine\player\Player;
use pocketmine\plugin\PluginBase;
use kim\present\utils\session\Cooldown;
use kim\present\utils\session\PlayerMap;

final class MyPlugin extends PluginBase{
    /** @var PlayerMap<Vector3> player => last clicked block */
    private PlayerMap $lastClicks;
    private Cooldown $useCooldown;

    protected function onEnable() : void{
        $this->lastClicks = new PlayerMap($this);   // emptied on quit, closed on plugin disable
        $this->useCooldown = Cooldown::seconds(1.5); // or Cooldown::ticks(30)
    }

    public function onUse(Player $player, Vector3 $pos) : void{
        if(!$this->useCooldown->try($player)){
            $seconds = round($this->useCooldown->getRemainingSeconds($player), 1);
            $player->sendMessage("Wait $seconds seconds");
            return;
        }
        $this->lastClicks->set($player, $pos);
    }
}
  • PlayerMap removes a player's entry when they quit (at MONITOR, so other quit handlers can still read it) and closes itself when the plugin is disabled. onRemove(fn(Player $player, $value) => ...) runs for every entry that leaves the map, for example to close a menu. An exception thrown by that callback is logged and does not stop clear() or close(). Removing entries while iterating the map is safe.
  • Cooldown needs no listener. It is keyed by the player's UUID, so reconnecting does not reset a running cooldown, and it prunes expired entries by itself.
  • A cooldown counts server ticks. When the server lags, a cooldown lasts longer than the same time on the clock.
  • PlayerMap is keyed by the player's runtime id, which is never reused, so a value never leaks to a reconnecting player. The entry is removed on quit instead.

📚 Examples

Task session with a timeout
use pocketmine\event\player\PlayerChatEvent;
use pocketmine\player\Player;
use pocketmine\scheduler\ClosureTask;
use pocketmine\scheduler\TaskHandler;
use kim\present\utils\session\Session;
use kim\present\utils\session\SessionManager;
use kim\present\utils\session\SessionTerminateReasons;
use kim\present\utils\session\listener\attribute\SessionEventHandler;

/**
 * @extends Session<SessionManager<MyPlugin, ConfirmSession>>
 */
final class ConfirmSession extends Session{
    private ?TaskHandler $timeout = null;

    /**
     * @param SessionManager<MyPlugin, ConfirmSession> $sessionManager
     */
    public function __construct(SessionManager $sessionManager, Player $player, private readonly string $question){
        parent::__construct($sessionManager, $player);
    }

    protected function onStart() : void{
        $this->getPlayer()->sendMessage("$this->question Type 'yes' within 10 seconds.");
        $this->timeout = $this->sessionManager->getPlugin()->getScheduler()->scheduleDelayedTask(
            new ClosureTask(fn() => $this->terminate(SessionTerminateReasons::TIMEOUT)),
            20 * 10
        );
    }

    protected function onTerminate(string $reason) : void{
        $this->timeout?->cancel();
    }

    #[SessionEventHandler(PlayerChatEvent::class)]
    public function onChat(PlayerChatEvent $event) : void{
        if(strtolower($event->getMessage()) === "yes"){
            $event->cancel();
            $this->terminate(SessionTerminateReasons::COMPLETED);
        }
    }
}

// $this->confirms = new SessionManager($this, ConfirmSession::class);
// $this->confirms->createSession($player, "Delete your island?"); // extra arguments go to the constructor

Extra arguments of createSession($player, ...$args) are forwarded to your session constructor after the manager and the player, so a task session can receive any data it needs. A lifecycle session cannot use them, because the manager creates it automatically.

Reacting to termination
$this->sessionManager->onSessionTerminated(function(WorldEditSession $session, string $reason) : void{
    if($reason === SessionTerminateReasons::PLAYER_QUIT){
        $this->database->save($session->getPlayer()->getName(), $session->exportState());
    }
});

The callback may type its parameter with your concrete session class. The order is always: Session::onTerminate() first, then the callback, each exactly once.

📖 API reference

SessionManager

Namespace kim\present\utils\session. One manager per session class. Generic as SessionManager<TPlugin, TSession>.

Method Description
__construct(PluginBase $plugin, string $sessionClass) Registers the session's event handlers and the plugin-disable hook. Lifecycle sessions are also created for players already online. Throws InvalidArgumentException if the class is not a Session, or is a SequenceSession (use SessionSequence)
getPlugin(): TPlugin The plugin that owns this manager
getSessionClass(): class-string<TSession> The session class this manager handles
getSession(Player|int $playerOrId): ?TSession The active session, or null. Accepts a player or a runtime ID
getSessionOrThrow(Player|int $playerOrId): TSession The active session, or RuntimeException if none exists
createSession(Player $player, mixed ...$args): ?TSession Creates and starts a session, or returns the existing one. null if the player is disconnected, the start failed (logged) or the session ended in onStart(). Throws LogicException when closed
getOrCreateSession(Player $player): ?TSession The existing session, or a newly created one
getAllSessions(): list<TSession> Every active session
removeSession(Session|Player|int $session, string $reason = MANUAL): void Terminates and removes a session, given as the session, the player or the runtime ID. No-op if there is none, or if the given Session object is stale
terminateAll(string $reason = MANUAL): int Terminates every session, returns how many
onSessionCreated(Closure $callback): self fn(TSession): void, called after a session is created and started, and at once for every existing session. Single slot: a new callback replaces the old one. Not called when the start failed
onSessionTerminated(Closure $callback): self fn(TSession, string $reason): void, called after onTerminate(). Single slot
close(string $reason = PLUGIN_DISABLE): void Terminates every session and detaches all listeners. Idempotent
isClosed(): bool Whether close() has been called

Session

Method Description
getPlayer(): Player The owning player
isActive(): bool true between the start and terminate()
terminate(string $reason = MANUAL) Removes this session from its manager. No-op if it is already terminated
start(): void Internal, called by the manager. Throws LogicException after the session was terminated
protected onStart(): void Hook, called once when the session starts
protected onTerminate(string $reason) Hook, called once when the session ends

PlayerMap<T>

Method Description
__construct(PluginBase $plugin) Removes entries on quit and closes the map when the plugin is disabled
get(Player $player): ?T The value, or null
getOrCreate(Player $player, Closure $factory): T The value, created by fn(Player): T and stored first if missing
set(Player $player, T $value): void Stores a value. Ignored for a disconnected player. Throws LogicException when closed
has(Player $player): bool Whether the player has a value, even null
remove(Player $player): ?T Removes and returns the value
onRemove(Closure $callback): self fn(Player, T): void, called for every entry that leaves the map (not on set()). Exceptions are logged
clear(): void / close(): void / isClosed(): bool Removes every entry / also detaches the listeners
getPlayers(): list<Player>, count(), foreach Players with a value, size, Player => T iteration (entries may be removed meanwhile)

Cooldown

Method Description
static ticks(int $ticks, ?Closure $clock = null): Cooldown A cooldown of $ticks server ticks. $clock is fn(): int returning the current tick, by default the server tick (useful in tests)
static seconds(float $seconds, ?Closure $clock = null): Cooldown Same, in seconds rounded up to ticks
getDuration(): int The cooldown length in ticks
try(Player $player): bool Starts the cooldown and returns true if ready, else false
isReady(Player $player): bool Whether the cooldown is over
getRemainingTicks(Player $player): int Ticks left, 0 if ready
getRemainingSeconds(Player $player): float Seconds left at the nominal tick rate, 0.0 if ready
start(Player $player): void Starts or restarts the cooldown
remove(Player $player): void Ends one player's cooldown. reset() does the same and is deprecated
clear(): void Ends every cooldown

Both factories throw InvalidArgumentException for a negative value.

SequenceSession and SessionSequence

Namespace kim\present\utils\session\sequence.

Method Description
SequenceSession::next(string $reason = COMPLETED) Terminates this session and starts the next step, or calls onComplete on the last step. No-op when the session is no longer active
new SessionSequence(PluginBase $plugin, string ...$sessionClasses) Steps in order. Throws InvalidArgumentException for no classes, a class that is not a SequenceSession, or one that implements LifecycleSession
start(Player $player): ?SequenceSession Starts from the first step. Returns that step's session, or null if it could not start
startFrom(Player $player, int|string $step): ?SequenceSession Starts from a 0-based index or a session class name. null if it could not start. Throws InvalidArgumentException for an unknown step
getCurrentStep(Player $player): ?int 0-based index of the player's current step, or null
getSessionClassAt(int $index): ?string The session class of a step, or null if out of range
onComplete(Closure $callback): self fn(Player): void, called when the last step calls next()
terminateAll(string $reason = MANUAL): int Terminates every active session of every step, returns how many
close(string $reason = PLUGIN_DISABLE): void Closes every step's manager. Also done automatically when the plugin is disabled

SequenceSessionManager is final and internal: it is only created by SessionSequence.

#[SessionEventHandler]

#[SessionEventHandler(string $eventClass, int $priority = EventPriority::NORMAL, bool $handleCancelled = false)]

Can be repeated on one method for different events. handleCancelled defaults to false, like PocketMine-MP. The method must be public and take exactly one non-nullable Event parameter that accepts $eventClass, and the event must have a player (getPlayer() or getEntity(), see Which session receives an event). Otherwise the handler is skipped with a warning in the plugin log.

Termination reasons

terminate(string $reason) accepts any string. Built-in constants are provided by SessionTerminateReasons, a final class: use its constants, it cannot be implemented.

Constant Value Description
MANUAL "manual" Explicitly terminated by plugin code
PLAYER_QUIT "player_quit" Player left the server
PLUGIN_DISABLE "plugin_disable" Owning plugin was disabled
START_FAILED "start_failed" onStart() threw: onTerminate() runs with this reason after the failed start
COMPLETED "completed" Session reached its end state
CANCELLED "cancelled" Session abandoned before completion
TIMEOUT "timeout" Session exceeded allotted time
RESTART "restart" Session terminated to restart fresh
MAINTENANCE "maintenance" Server maintenance

🩺 Troubleshooting

My handler is never called

  • The method must be public, take exactly one non-nullable Event parameter, and that type must accept the attribute's event class. Otherwise the plugin log has a warning from when the manager was created.
  • The event must have a player: getPlayer(), or getEntity() returning a Player. For damage events the session of the victim receives it, not the attacker's.
  • The event may be cancelled by another plugin. Handlers skip cancelled events unless handleCancelled: true.
  • The player needs a session in this manager: a lifecycle session, or one you created with createSession().

getSession() or createSession() returns null

  • The player disconnected (a kicked player gets no session).
  • The manager is closed (its plugin was disabled). createSession() throws LogicException in that case.
  • The session failed to start: look for Failed to start session in the plugin log. A session that terminated itself in onStart() also yields null.
  • The session already ended: the player quit, it timed out, or removeSession() removed it.

🏗️ Architecture

Class diagram, event flow and components
classDiagram
direction LR

class Session {
    <<abstract>>
    -Player player
    -SessionManager sessionManager
    -bool active
    +getPlayer() Player
    +isActive() bool
    +start() void
    +terminate(reason) void
    +finalizeTermination(reason) void
    #onStart() void
    #onTerminate(reason) void
}

class SequenceSession {
    <<abstract>>
    #next(reason) void
}

class LifecycleSession {
    <<interface>>
}

class SessionManager~TPlugin, TSession~ {
    -array sessions
    -list eventBindingList
    +getPlugin() TPlugin
    +getSession(playerOrId) TSession?
    +getSessionOrThrow(playerOrId) TSession
    +getOrCreateSession(player) TSession?
    +createSession(player, ...args) TSession?
    +getAllSessions() list~TSession~
    +removeSession(session, reason) void
    +terminateAll(reason) int
    +close(reason) void
    +isClosed() bool
    +getSessionClass() class-string
    +onSessionCreated(callback) self
    +onSessionTerminated(callback) self
}

class SequenceSessionManager {
    <<final>>
    +setNext(manager) void
    +setOnExhausted(callback) void
    +progressNext(player, reason) void
}

class SessionSequence {
    +start(player) SequenceSession?
    +startFrom(player, step) SequenceSession?
    +getCurrentStep(player) int?
    +close(reason) void
    +onComplete(callback) self
    +terminateAll(reason) int
}

class SessionEventListenerRegistry {
    <<singleton>>
    -array listeners
    +attachBinding(binding, plugin) void
    +detachBinding(binding) void
}

class SessionEventListener {
    -array eventDispatchers
    -RegisteredListener registeredListener
    +onEvent(event) void
    +attachBinding(dispatcher) void
    +detachBinding(dispatcher) void
    +hasDispatchers() bool
}

class BaseSessionEventDispatcher {
    <<abstract>>
    +string eventKey
    +string eventClass
    +int priority
    +bool handleCancelled
    +string methodName
    +resolveTarget(player) object?
    +dispatch(event, target) void
}

class SessionMethodDispatcher {
    +dispatch(event, target) void
}

class ManagerMethodDispatcher {
    +dispatch(event, target) void
}

class SessionEventHandler {
    <<attribute>>
    +string eventClass
    +int priority
    +bool handleCancelled
}

Session <|-- SequenceSession
Session <|-- LifecycleSession
SessionManager <|-- SequenceSessionManager
SessionSequence --> SequenceSessionManager : creates and chains
SequenceSessionManager --> SequenceSession : manages
SessionManager --> Session : manages
SessionManager --> SessionEventListenerRegistry : registers via
SessionEventListenerRegistry --> SessionEventListener : owns one per plugin and eventKey
SessionEventListener --> BaseSessionEventDispatcher : dispatches to
BaseSessionEventDispatcher <|-- SessionMethodDispatcher
BaseSessionEventDispatcher <|-- ManagerMethodDispatcher
SessionMethodDispatcher ..> SessionEventHandler : created from
Loading

Event flow

PMMP fires event
  → SessionEventListener::onEvent()
    → player of the event (getPlayer(), else getEntity()); none → skipped
    → resolve every dispatcher's target first (so a session created meanwhile does not get this event)
    → [cancelled mid-dispatch? stop if handleCancelled=false]
    → BaseSessionEventDispatcher::dispatch()
      ├─ SessionMethodDispatcher → the player's session → Session::{methodName}(event)
      └─ ManagerMethodDispatcher → SessionManager::{methodName}(event)

Components

  • SessionEventListenerRegistry (singleton) keeps one PMMP listener per (plugin, eventClass, priority, handleCancelled). Several session types of the same plugin that handle the same event share it. A listener is never shared between plugins, because PocketMine-MP unregisters a plugin's listeners when it is disabled. This keeps the library safe when a single Composer copy is used by several plugins.
  • SessionEventListener is the registered listener for one such key. It finds the event's player (see Which session receives an event), resolves every dispatcher's target before the first handler runs, then routes the event to the dispatchers in registration order and respects cancellation mid-dispatch. The way to get the player is decided once per event class (PlayerSource), not on every event.
  • BaseSessionEventDispatcher holds the listener configuration and defines dispatch(). SessionMethodDispatcher calls the bound method on the player's active session; ManagerMethodDispatcher calls a method on the manager (used for join/quit).
  • SequenceSessionManager is the internal, final manager SessionSequence creates per step. Do not use it directly.
  • Termination always runs onTerminate() and then the onSessionTerminated callback, once each, whether it was triggered by terminate(), removeSession(), a quit, a restart or close().

File structure

src/kim/present/utils/session/
├── Session.php
├── LifecycleSession.php
├── SessionManager.php
├── SessionTerminateReasons.php
├── PlayerMap.php
├── Cooldown.php
├── sequence/
│   ├── SequenceSession.php
│   ├── SequenceSessionManager.php
│   └── SessionSequence.php
└── listener/
    ├── PlayerSource.php
    ├── SessionEventListener.php
    ├── SessionEventListenerRegistry.php
    ├── attribute/
    │   └── SessionEventHandler.php
    └── dispatcher/
        ├── BaseSessionEventDispatcher.php
        ├── SessionMethodDispatcher.php
        └── ManagerMethodDispatcher.php

🧪 Development

composer install --ignore-platform-req='ext-*'
composer analyse # PHPStan level 9 with strict rules
composer test

The tests use the real axolotl-pm/pocketmine-mp code without its native extensions.

📄 License

Distributed under the MIT License. See LICENSE for more information.