PHPackages                             phossa2/event - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. phossa2/event

AbandonedArchivedLibrary[Utility &amp; Helpers](/categories/utility)

phossa2/event
=============

PSR-14 event manager implementation libraray for PHP

2.1.6(9y ago)10205.7k↑44.4%23MITPHPPHP &gt;=5.4.0

Since Jul 5Pushed 6y ago3 watchersCompare

[ Source](https://github.com/phossa2/event)[ Packagist](https://packagist.org/packages/phossa2/event)[ Docs](https://github.com/phossa2/event)[ RSS](/packages/phossa2-event/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (2)Versions (11)Used By (3)

phossa2/event \[ABANDONED\]
===========================

[](#phossa2event-abandoned)

**PLEASE USE [phoole/event](https://github.com/phoole/event) library instead**

[![Build Status](https://camo.githubusercontent.com/fc3c8689075b12497e85c68b70937b60c9d74872b8c3b23697a11acc85a571a6/68747470733a2f2f7472617669732d63692e6f72672f70686f737361322f6576656e742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/phossa2/event)[![Code Quality](https://camo.githubusercontent.com/8b0b7b0eb993a210774a3735efb7c58a1de3eb563df466947fc1358c8e1bfc29/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70686f737361322f6576656e742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/phossa2/event/)[![Code Climate](https://camo.githubusercontent.com/79db1467e7683ddec6928a738ef6910ad5462f675c3c188c49feaa3d99ebb6f0/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f70686f737361322f6576656e742f6261646765732f6770612e737667)](https://codeclimate.com/github/phossa2/event)[![PHP 7 ready](https://camo.githubusercontent.com/ee7719a2bb909f33fbd4a3bff5a1d4b5ce2ff70f6f7d54435d759f4cb62f1404/687474703a2f2f7068703772656164792e74696d6573706c696e7465722e63682f70686f737361322f6576656e742f6d61737465722f62616467652e737667)](https://travis-ci.org/phossa2/event)[![HHVM](https://camo.githubusercontent.com/aa3b95727b0e5ba35a79af44d0ad8e56aaa79519c5bfd2c1e1b1fbddaf5ed024/68747470733a2f2f696d672e736869656c64732e696f2f6868766d2f70686f737361322f6576656e742e7376673f7374796c653d666c6174)](http://hhvm.h4cc.de/package/phossa2/event)[![Latest Stable Version](https://camo.githubusercontent.com/05197343c92649b3107887906d4740035a2bf14929b73971401a911b1264aa2e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f767072652f70686f737361322f6576656e742e7376673f7374796c653d666c6174)](https://packagist.org/packages/phossa2/event)[![License](https://camo.githubusercontent.com/4fc6538ded72843e26a272d300ce4c95da083ce92576e10e4fdd505d579a8125/68747470733a2f2f696d672e736869656c64732e696f2f3a6c6963656e73652d6d69742d626c75652e737667)](http://mit-license.org/)

**phossa2/event** is a PSR-14 event manager library for PHP.

It requires PHP 5.4, supports PHP 7.0+ and HHVM. It is compliant with [PSR-1](http://www.php-fig.org/psr/psr-1/ "PSR-1: Basic Coding Standard"), [PSR-2](http://www.php-fig.org/psr/psr-2/ "PSR-2: Coding Style Guide"), [PSR-4](http://www.php-fig.org/psr/psr-4/ "PSR-4: Autoloader") and the upcoming [PSR-14](https://github.com/php-fig/fig-standards/blob/master/proposed/event-manager.md "Event Manager")

Installation
------------

[](#installation)

Install via the `composer` utility.

```
composer require "phossa2/event=2.1.*"

```

or add the following lines to your `composer.json`

```
{
    "require": {
       "phossa2/event": "^2.1.0"
    }
}
```

Features
--------

[](#features)

- Event name [globbing](#glob).
- Built-in *multiple* [shared event managers](#shared) support.
- [Attach and detach](#attach) listeners.
- [Static event manager](#static) support.
- Built-in [class level](#class) events support.
- Able to [limit](#limit) number of times of an event callable executed.

Usage
-----

[](#usage)

- Quick start

    ```
    use Phossa2\Event\EventDispatcher;

    // event dispatcher
    $events = new EventDispatcher();

    // bind event with a callback
    $events->attach('login.success', function($evt) {
        echo "logged in as ". $evt->getParam('username');
    });

    // bind event with a callable
    $events->attach('login.attempt', [$logger, 'logEvent']);

    // unbind an event
    $events->clearListeners('login.attempt');

    // fire the trigger
    $events->trigger('login.success');
    ```
- Event name globbing

    Event name globbing means callables of the binding 'login.\*' will also be triggered when triggering event 'login.success'.

    ```
    // bind 'login.*' with callables
    $events->attach('login.*', function($evt) {
        echo $evt->getName();
    });

    // trigger 'login.atttempt' will also trigger callables of 'login.*'
    $events->trigger('login.attempt');
    ```

    The globbing rules are similiar to the PHP function `glob()`, where

    - `*` in the string means any chars except the dot.
    - If `*` at the end, will match any chars including the dot. e.g. `login.*`will match 'login.attempt.before'.
    - `.` means the dot.
    - one-char-string `*` means match any string (including the dot).

    **Note:** Name globbing **ONLY** happens when event is being triggered. Binding or unbinding events only affect the *EXACT* event name.

    ```
    // unbind the exact 'login.*'
    $events->clearListeners('login.*');
    ```
- Shared event manager support

    Class `EventDispatcher` implements the `Phossa2\Shared\Shareable\ShareableInterface`.

    `ShareableInterface` is an extended version of singleton pattern. Instead of supporting only one shared instance, Classes implements `ShareableInterface`may have shared instance for different `scope`.

    ```
    // global event manager, global scope is ''
    $globalEvents = EventDispatcher::getShareable();

    // shared event manager in scope 'MVC'
    $mvcEvents = EventDispatcher::getShareable('MVC');

    // an event manager instance, which has scope 'MVC'
    $events = new EventDispatcher('MVC');

    // in scope MVC ?
    var_dump($events->hasScope('MVC')); // true

    // in global scope ?
    var_dump($events->hasScope()); // true
    ```

    Callables bound to a shared manager will also be triggered if an event manager instance has the same scope.

    ```
    // shared event manager in scope 'MVC'
    $mvcEvents = EventDispatcher::getShareable('MVC');

    // bind with pirority 100 (highest priority)
    $mvcEvents->attach('*', function($evt) {
        echo "mvc";
    }, 100);

    // create a new instance within the MVC scope
    $events = new EventDispatcher('MVC');

    // bind with default priority 0
    $events->attach('test', function($evt) {
        echo "test";
    });

    // will also trigger matched events in $mvcEvents
    $events->trigger("test");
    ```

    Event manager instance can have multiple scopes, either specified during the instantiation or using `addScope()`.

    ```
    // create an event manager with 2 scopes
    $events = new EventDispatcher(['MVC', 'AnotherScope']);

    // add another scope
    $events->addScope('thirdScope');
    ```

    Couple of helper methods are provided for on/off/trigger events with shared managers.

    ```
    // bind a callable to global event manager
    EventDispatcher::onGlobalEvent('login.success', function() {});

    // use interface name as a scope
    EventDispatcher::onEvent(
        'Psr\\Log\\LoggerInterface', // scope
        'log.error', // event name
        function () {}
    );

    // unbind all callables of event 'log.error' in a scope
    EventDispatcher::offEvent(
        'Psr\\Log\\LoggerInterface',
        'log.error'
    );

    // unbind *ALL* events in global scope
    EventDispatcher::offGlobalEvent();
    ```
- Attaching a listener

    `Listener` implements the `ListenerInterface`. Or in short, provides a method `eventsListening()`.

    ```
    use Phossa2\Event\Interfaces\ListenerInterface;

    class myListener implements ListenerInterface
    {
        public function eventsListening()
        {
            return [
                // one method of $this
                eventName1 => 'method1',

                // 2 methods
                eventName2 => ['callable1', 'method2'],

                // priority 20 and in a 'mvcScope' scope
                eventName2 => ['method2', 20, 'mvcScope'], // with priority 20

                eventName3 => [
                    ['method3', 50],
                    ['method4', 70, 'anotherScope']
                ]
            ];
        }
    }
    ```

    `EventDispatcher::attachListener()` can be used to bind events defined in `eventsListening()` instead of using `EventDispatcher::attach()` to bind each event manually.

    ```
    $events = new EventDispatcher();

    $listener = new \myListener();

    // bind all events defined in $listener->eventsListening()
    $events->attachListener($listener);

    // will call $listener->method1()
    $events->trigger('eventName1');
    ```
- Using event manager statically

    `StaticEventDispatcher` is a static wrapper for an `EventDispatcher` slave.

    ```
    StaticEventDispatcher::attach('*', function($evt) {
        echo 'event ' . $evt->getName();
    });

    // will print 'event test'
    StaticEventDispatcher::trigger('test');
    ```

    `StaticEventDispatcher` is not the same as global event manager. `StaticEventDispatcher` has a default slave which is a shared event manager in scope `'__STATIC__'`. While global event manager is the shared event manager in global scope `''`.

    User may set another event manager to replace the default slave.

    ```
    StaticEventDispatcher::setEventManager(new EventDispatcher());
    ```
- `EventCapableAbstract`

    `EventCapableAbstract` implements both `ListenerInterface` and `EventCapableInterface`. It will do the following when `triggerEvent()`is called,

    - Get the event manager. If it is not set yet, create one default event manager with current classname as scope.
    - Attach events defined in `eventsListening()` if not yet.
    - Trigger the event and processed by the event manager and all of the shared managers of its scopes.

    ```
    class LoginController extends EventCapableAbstract
    {
        public function login() {

            // failed
            if (!$this->trigger('login.pre')) {
                return;
            }

            // ...
        }

        public function beforeLogin() {
            // ...
        }

        public function eventsListening()
        {
            return [
                'login.pre' => 'beforeLogin'
            ];
        }
    }
    ```
- `EventableExtensionAbstract` and `EventableExtensionCapableAbstract`

    `EventableExtensionCapableAbstract` is the base class supporting events and extensions.

    Detail usage can be found in [phossa2/cache](https://github.com/phossa2/cache)`Phossa2\Cache\CachePool` extends `EventableExtensionCapableAbstract` and `Phossa2\Cache\Extension\ByPass` extends `EventableExtensionAbstract`.

    Or look at [phossa2/route](https://github.com/phossa2/route).
- Class or interface level events support

    Class or interface name can be used as the `scope`. When events bound to these kind of scopes, any events triggered by child class will also search callables defined in parent class/interface level shared event managers.

    ```
    // define event '*' for interface 'MyInterface'
    EventDispatcher::onEvent(
        'MyInterface', '*', function() { echo "MyInterface"; }, 60
    );
    ```

    Extends `EventCapableAbstract`.

    ```
    class MyClass extends EventCapableAbstract implements MyInterface
    {
        public function myMethod()
        {
            echo "myMethod";
        }

        public function eventsListening()/*# : array */
        {
            return [
                // priority 20
                'afterTest' => ['myMethod', 20]
            ];
        }
    }

    $obj = new MyClass();

    // will trigger callable 'myMethod' and handlers for 'MyInterface'
    $obj->trigger('afterTest');
    ```
- Execute callable for limited times

    ```
    // bind a callable for executing only once
    $events->one('user.login', function(Event $evt) {
        // ...
    });

    // 3 times
    $events->many(3, 'user.tag', function(Event $evt) {
        // ...
    });
    ```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) from more information.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTE](CONTRIBUTE.md) for more information.

Dependencies
------------

[](#dependencies)

- PHP &gt;= 5.4.0
- phossa2/shared &gt;= 2.0.21

License
-------

[](#license)

[MIT License](http://mit-license.org/)

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity40

Moderate usage in the ecosystem

Community18

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 89.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

9

Last Release

3553d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6e0ecf2ab11402101d86a36b457973b81149757a53a67dd048bbfb9025890abf?d=identicon)[phossa2](/maintainers/phossa2)

---

Top Contributors

[![phossa](https://avatars.githubusercontent.com/u/8499165?v=4)](https://github.com/phossa "phossa (52 commits)")[![phossa2](https://avatars.githubusercontent.com/u/19922046?v=4)](https://github.com/phossa2 "phossa2 (5 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

psreventpsr-14event managerphossa

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phossa2-event/health.svg)

```
[![Health](https://phpackages.com/badges/phossa2-event/health.svg)](https://phpackages.com/packages/phossa2-event)
```

###  Alternatives

[doctrine/event-manager

The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.

6.1k501.1M115](/packages/doctrine-event-manager)[psr/event-dispatcher

Standard interfaces for event handling.

2.3k618.8M865](/packages/psr-event-dispatcher)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
