PHP code example of laxity7 / yii2-event-service

1. Go to this page and download the library: Download laxity7/yii2-event-service 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/ */

    

laxity7 / yii2-event-service example snippets


namespace App\Events;

use yii\base\Event;

final readonly class PaymentEvent
{
    public function __construct(
        public float $amount,
        public string $currency,
        public string $description,
    ) {
    }
}

namespace App\Events\listeners;

use App\Events\PaymentEvent;

final class PaymentListener
{
    //public function __invoke(PaymentEvent $event): void
    public function handle(PaymentEvent $event): void
    {
        Yii::info('Event: ' . get_class($event) . ' Trigger: ' . __METHOD__, __METHOD__);
    }
}

'components' => [
    'eventDispatcher' => [
         'class' => \Laxity7\Yii2\Components\EventServiceProvider::class,
         'listen' => [
             \App\Events\PaymentEvent::class => [
                 \App\Events\listeners\PaymentListener::class, // listener class
                 function (\App\Events\PaymentEvent $event) { // closure
                    Yii::info('Event: ' . get_class($event) . ' Trigger: ' . __METHOD__, __METHOD__);
                 },
             ],
         ],
    ],
],

use App\Events\PaymentEvent;
use Laxity7\Yii2\Components\Event;

$event = new PaymentEvent(100, 'USD', 'Payment for goods');
\Yii::$app->eventDispatcher->dispatch($event);
// or use the helper
Event::dispatch($event);