PHP code example of phpdevcommunity / psr14-event-dispatcher

1. Go to this page and download the library: Download phpdevcommunity/psr14-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/ */

    

phpdevcommunity / psr14-event-dispatcher example snippets




namespace App\Event;

use PhpDevCommunity\Listener\Event;

/**
 * Class PreCreateEvent
 * @package App\Event
 */
class PreCreateEvent extends Event
{
    private object $object;

    /**
     * PreCreateEvent constructor.
     * 
     * @param object $object
     */
    public function __construct(object $object)
    {
        $this->object = $object;
    }

    /**
     * Get the associated object.
     *
     * @return object
     */
    public function getObject(): object
    {
        return $this->object;
    }
}



namespace App\Listener;

use App\Entity\User;
use App\Event\PreCreateEvent;

/**
 * Class UserListener
 * @package App\Listener
 */
class UserListener
{
    /**
     * Handle the event.
     * 
     * @param PreCreateEvent $event
     */
    public function __invoke(PreCreateEvent $event): void
    {
        $object = $event->getObject();

        if ($object instanceof User) {
            // Perform actions with the User object
        }
    }
}



use App\Event\PreCreateEvent;
use App\Listener\UserListener;

// Create the listener provider and register the listener
$listenerProvider = (new ListenerProvider())
    ->addListener(PreCreateEvent::class, new UserListener());

// Create the event dispatcher with the listener provider
$dispatcher = new \PhpDevCommunity\Listener\EventDispatcher($listenerProvider);

// Dispatch the event after saving a user to the database
$dispatcher->dispatch(new PreCreateEvent($user));