Event Listener

Event listeners allow additional code to be executed when certain events occur within the software such as a user being created or view being rendered. This provides extensibility allowing additional functionality to be included within packages without having write access to that package.

Within terminal, run the following command:

apex create listener disaster disaster-users --routing-key users.profiles

Open the newly generated file at /src/Disaster/Listeners/DisasterUsers.php, and at the top within the use declarations add the line:

use App\Disaster\Models\Volunteer;

The class also contains a $routing_key property with a value of users.profiles. Messages are dispatched when certain events occur and always consist of three parts seperated by a period, which generally should be PACKAGE.ALIAS.METHOD. For example, the apex/users package will dispatch a message when a user is created to the routing key users.profiles.postCreate.

Apex will then automatically instantiate all event listeners with a routing key of users.profiles and look for a postCreate() method within it, which will be executed if it exists. Within the PHP class, delete the example() method and add the method:

[data-line=55]
/**
 * User created
 */
public function postCreate(MessageRequestInterface $msg, FeHandlerInterface $handler)
{

    // Get uuid
    $uuid = $msg->getParams();

    // Add volunteer
    Volunteer::insert([
        'uuid' => $uuid
    ]);

}

Now every time a user is created the above method will be executed, adding an record into the `disaster_volunteers database table that was previously created. For exact routing keys and method available you will need to consult the package's documentation.