PHP code example of ostrolucky / app-event-dispatcher

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

    

ostrolucky / app-event-dispatcher example snippets


$dispatcher = new Ostrolucky\AppEventDispatcher\AppEventDispatcher();
$dispatcher->attach('my.event.name', function(array $parameter1, \stdClass $parameter2) {
    var_dump($parameter1, $parameter2);
}));
$dispatcher->dispatch('my.event.name', ['hey'], new \stdClass);

    class AppBundle extends Bundle
    {
        public function build(ContainerBuilder $container)
        {
            parent::build($container);
            $container->addCompilerPass(new Ostrolucky\AppEventDispatcher\Symfony\DependencyInjection\RegisterListenersPass());
        }
    }
    

// symfony event dispatcher
$event = new \Symfony\Component\EventDispatcher\GenericEvent(null, [
    'group' => null, 'user' => new User(), 'array' => [3, 5]
    ]
);
$eventDispatcher->dispatch('some.event', $event);

// vs. this dispatcher
$appEventDisdpatcher->dispatch('some.event', null, new User(), [3, 5]);

public function onSomeEvent(GenericEvent $event) {
    $arguments = $event->getArguments();
    if (isset($arguments['group']) && !$arguments['group'] instanceof Group) {
        throw new \InvalidArgumentException('Invalid group');
    }
    
    if (isset($arguments['user']) && !$arguments['user'] instanceof User) {
        throw new \InvalidArgumentException('Invalid user');
    }
    
    if (!is_array($arguments['array'])) {
        throw new \InvalidArgumentException('Invalid array');
    }
    
    /** @var Group $group */
    $group = $arguments['group'] ?? null;
    /** @var User $user */
    $user = $arguments['user'] ?? null;
    $array = $arguments['array'];
    
    // do the actual work...
}

public function onSomeEvent(?Group $group, ?User $user, array $array) {
    // do the actual work
}