PHP code example of ssnepenthe / wp-event-dispatcher

1. Go to this page and download the library: Download ssnepenthe/wp-event-dispatcher 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/ */

    

ssnepenthe / wp-event-dispatcher example snippets


add_action('my_plugin_initialized', function () {
    // ...
});

do_action('my_plugin_initialized');

class MyPluginInitialized
{
}

$eventDispatcher = new EventDispatcher();
$eventDispatcher->addListener(MyPluginInitialized::class, function (MyPluginInitialized $event) {
    // ...
});

$eventDispatcher->dispatch(new MyPluginInitialized());

add_filter('my_plugin_filtered_value', function ($value) {
    if (is_string($value)) {
        $value = modifyValue($value);
    }

    return $value;
});

$default = 'some string';
$value = apply_filters('my_plugin_filtered_value', $default);

if (! is_string($value)) {
    $value = $default;
}

class MyPluginFilteredValue
{
    public function __construct(public string $value)
    {
    }
}

$eventDispatcher = new EventDispatcher();
$eventDispatcher->addListener(MyPluginFilteredValue::class, function (MyPluginFilteredValue $event) {
    $event->value = modifyValue($event->value);
});

$event = new MyPluginFilteredValue('some string');
$eventDispatcher->dispatch($event);
$value = $event->value;

return [
    'the_content' => 'onTheContent',
];

return [
    'the_content' => ['onTheContent', 20],
];

return [
    'the_content' => [
        ['onTheContent', 20],
        ['alsoOnTheContent'],
    ],
];

class PostContentSubscriber implements SubscriberInterface
{
    public function getSubscribedEvents(): array
    {
        return [
            'the_content' => [
                ['appendSomething'],
                ['prependAnotherThing', 20],
            ],
        ];
    }

    public function appendSomething($content)
    {
        return $content . ' something';
    }

    public function prependAnotherThing($content)
    {
        return 'another thing ' . $content;
    }
}

$eventDispatcher->addSubscriber(new PostContentSubscriber());