PHP code example of phossa2 / event

1. Go to this page and download the library: Download phossa2/event library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phossa2 / event example snippets


  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');
  

  // 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');
  

  // unbind the exact 'login.*'
  $events->clearListeners('login.*');
  

  // 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
  

  // 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");
  

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

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

  // 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();
  

  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']
              ]
          ];
      }
  }
  

  $events = new EventDispatcher();

  $listener = new \myListener();

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

  // will call $listener->method1()
  $events->trigger('eventName1');
  

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

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

  StaticEventDispatcher::setEventManager(new EventDispatcher());
  

  class LoginController extends EventCapableAbstract
  {
      public function login() {

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

          // ...
      }

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

      public function eventsListening()
      {
          return [
              'login.pre' => 'beforeLogin'
          ];
      }
  }
  

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

  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');
  

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

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