Skip to content

Commit

Permalink
rename to Symbiotic
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Surkov committed Aug 29, 2021
0 parents commit e019b88
Show file tree
Hide file tree
Showing 6 changed files with 253 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 SymbioticPHP

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
88 changes: 88 additions & 0 deletions README.RU.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
## Расширение интерфейсов для диспетчера событий PSR-14

Добавлен метод добавления слушателей с передачей имени события и возможностью передавать в качестве слушателя название класса.
Такой подход позволяет избежать использования Рефлексии при добавлении слушателей, а также ненужных объектов замыканий.

## Установка
```
composer require symbiotic/event-contracts
Можно сразу поставить реализацию интерфейсов "symbiotic/event"
```
## Описание
```php
use \Psr\EventDispatcher\ListenerProviderInterface;

interface ListenersInterface extends ListenerProviderInterface
{
/**
* @param string $event имя класса или произвольное имя события
* (при произвольного названии нужен кастомный диспетчер не по PSR)
*
* @param \Closure|string $handler функция или имя класса обработчика
* Класс обработчика событий должен реализовать метод handle (...$params) или __invoke(...$params)
* <Важно:> При добавлении слушателей в качестве названий классов, вы должны будете их при отдаче в методе getListenersForEvent() адаптировать в \Closure!!!
*
* @return void
*/
public function add(string $event, $handler): void;
}
```

Примерная реализация \Closure обертки:
```php

$listenerResolver = function($listener) {
return function(object $event) use ($listener) {
// if classname
if(is_string($listener) && class_exists($listener)) {
$listener = new $listener();
return $listener->handle($event);
} elseif(is_callable($listener)) {
return $listener($event);
}
};
};
// вы можете реализовать свою обертку прямо в методе getListenersForEvent() или прокинуть резолвер с контейнером PSR

class ListenerProvider implements Symbiotic\Event\ListenersInterface
{
protected $listenerResolver;

protected $listeners = [];

public function __construct(\Closure $listenerResolver = null)
{
$this->listenerResolver = $listenerResolver;
}

public function add(string $event, $handler): void
{
$this->listeners[$event][] = $handler;
}

public function getListenersForEvent(object $event): iterable
{
$parents = \class_parents($event);
$implements = \class_implements($event);
$classes = array_merge([\get_class($event)], $parents ?: [], $implements ?: []);
$listeners = [];
foreach ($classes as $v) {
$listeners = array_merge($listeners, isset($this->listeners[$v]) ? $this->listeners[$v] : []);
}
$wrapper = $this->listenerResolver;

return $wrapper ? array_map(function ($v) use ($wrapper) {
return $wrapper($v);
}, $listeners) : $listeners;

}
}


/**
* Прокидывание обертки
*/
$listenersProvider = new \Symbiotic\Event\ListenerProvider($listenerResolver);
```

88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
## Extend interfaces for PSR-14 Event Dispatcher
README.RU.md [РУССКОЕ ОПИСАНИЕ](https://github.com/symbiotic-php/event-contracts/blob/master/README.RU.md)

Added a method for adding listeners with passing the event name and the ability to pass the class name as a listener.
This approach avoids the use of Reflection when adding listeners, as well as unnecessary closure objects.

## Installation
```
composer require symbiotic/event-contracts
suggest symbiotic/event - reailsation
```
## Description
```php
use \Psr\EventDispatcher\ListenerProviderInterface;

interface ListenersInterface extends ListenerProviderInterface
{
/**
* @param string $event the class name or an arbitrary event name
* (with an arbitrary name, you need a custom dispatcher not for PSR)
*
* @param \Closure|string $handler function or class name of the handler
* The event handler class must implement the handle method (...$params) or __invoke(...$params)
* Important! When adding listeners as class names, you will need to adapt them to \Closure
* when you return them in the getListenersForEvent() method!!!
*
* @return void
*/
public function add(string $event, $handler): void;
}
```

Sample implementation of the \Closure wrapper:
```php

$listenerResolver = function($listener) {
return function(object $event) use ($listener) {
// if classname
if(is_string($listener) && class_exists($listener)) {
$listener = new $listener();
return $listener->handle($event);
} elseif(is_callable($listener)) {
return $listener($event);
}
};
};
// You can implement your wrapper directly in the getListenersForEvent() method or throw a resolver with a PSR container

class ListenerProvider implements Symbiotic\Event\ListenersInterface
{
protected $listenerResolver;

protected $listeners = [];

public function __construct(\Closure $listenerResolver = null)
{
$this->listenerResolver = $listenerResolver;
}

public function add(string $event, $handler): void
{
$this->listeners[$event][] = $handler;
}

public function getListenersForEvent(object $event): iterable
{
$parents = \class_parents($event);
$implements = \class_implements($event);
$classes = array_merge([\get_class($event)], $parents ?: [], $implements ?: []);
$listeners = [];
foreach ($classes as $v) {
$listeners = array_merge($listeners, isset($this->listeners[$v]) ? $this->listeners[$v] : []);
}
$wrapper = $this->listenerResolver;

return $wrapper ? array_map(function ($v) use ($wrapper) {
return $wrapper($v);
}, $listeners) : $listeners;

}
}

/**
* use resolver
**/
$listenersProvider = new \Symbiotic\Event\ListenerProvider($listenerResolver);
```
24 changes: 24 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "symbiotic/event-contracts",
"description": "Extend Interfaces for PSR 14 EventDispatcher",
"version": "1.0.1",
"type": "library",
"license": [
"MIT"
],
"keywords": [
"Symbiotic",
"PSR-14",
"Event Dispatcher",
"PSR-14 Event Dispatcher"
],
"require": {
"php": ">=7.2.0",
"psr/event-dispatcher": "^1.0"
},
"autoload": {
"psr-4": {
"\\Symbiotic\\Event\\": "src/Event/"
}
}
}
11 changes: 11 additions & 0 deletions src/Event/DispatcherInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symbiotic\Event;

use \Psr\EventDispatcher\EventDispatcherInterface;


interface DispatcherInterface extends EventDispatcherInterface
{

}
21 changes: 21 additions & 0 deletions src/Event/ListenersInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Symbiotic\Event;

use \Psr\EventDispatcher\ListenerProviderInterface;


interface ListenersInterface extends ListenerProviderInterface
{
/**
* @param string $event the class name or an arbitrary event name
* (with an arbitrary name, you need a custom dispatcher not for PSR)
*
* @param \Closure|string $handler function or class name of the handler
* The event handler class must implement the handle method (...$params) or __invoke(...$params)
* <Important:> When adding listeners as class names, you will need to adapt them to \Closure when you return them in the getListenersForEvent() method!!!
*
* @return void
*/
public function add(string $event, $handler): void;
}

0 comments on commit e019b88

Please sign in to comment.