Create class event App\Events\TestEvent::class
<?php
namespace App\Events;
class TestEvent
{
public string $hello;
public function __construct(string $hello = null)
{
$this->hello = $hello;
}
}
### Defining Listeners
Create class listener App\Listeners\TestListener::class
with magic method __invoke()
<?php
namespace App\Listeners;
use App\Events\TestEvent;
class TestListener
{
public function __construct(TestEvent $event)
{
}
public function __invoke(TestEvent $evet)
{
log_message('error', $evet->hello);
}
}
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Events\TestEvent;
use CodeIgniter\Events\Events;
class ProfileController extends BaseController
{
public function index()
{
Events::trigger(TestEvent::class, new TestEvent('world'));
}
Add as many arguments as you want and pass them to the listener in __construct
or __invoke
class ProfileController extends BaseController
{
public function index()
{
Events::trigger(TestEvent::class, new TestEvent('world'), $arg1 = 'args1', $arg2 = 'arg2', $argN = 'argN');
}
}
class TestListener
{
public function __construct(TestEvent $event, $arg1 = 'args1', $arg2 = 'arg2', $argN = 'argN')
{
}
public function __invoke(TestEvent $evet, $arg1, $arg2, $argN)
{
log_message('error', $evet->hello);
}
}
Create class App\Providers\EventServiceProvider
<?php
namespace App\Providers;
use CodeIgniter\Events\Events;
class EventServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected static $listen = [
\App\Events\TestEvent::class => [
\App\Listeners\TestListener::class,
]
];
public static function register()
{
foreach (static::$listen as $event => $listeners) {
foreach (array_unique($listeners, SORT_REGULAR) as $listener) {
Events::on($event, static function (...$callable) use ($listener) {
(new $listener(...$callable))(...$callable);
});
}
}
}
}
Finnaly you need to register App\Providers\EventServiceProvider
in config events app\Config\Events.php
see example bellow, and see the log
\App\Providers\EventServiceProvider::register();