# Events

## Introduction

Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Laravel Bash's events are signals, and signals are a doorbell, not a letterbox.

## Registering Listeners

Listeners are registered in `app/Providers/EventServiceProvider.sh`:

```bash
listen OrderShipped SendShipmentNotification
```

A listener is a function called `handle`, which gets the event's payload as JSON:

```bash
# app/Listeners/SendShipmentNotification.sh
SendShipmentNotification::handle() {
  local order_id
  order_id=$(jq -r .order_id <<< "$1")
  Log::info "Emailed the customer: order #$order_id has shipped (listener PID $$)"
}
```

## Dispatching Events

```bash
event OrderShipped order_id=1
```

Listeners run in a separate, long-lived process, which `./artisan dev` starts:

```bash
./sail artisan event:listen
```

## How It Works

### Ringing the doorbell

`event` appends the event to `storage/events/events.log`, then sends `SIGUSR1` to every process whose command line matches `artisan event:listen`:

```bash
printf '%s\t%s\n' "$name" "$payload" >> "$EVENT_LOG"
pkill -USR1 -f 'artisan event:listen'
```

### Answering the door

The listener sets a trap for the signal, then waits:

```bash
trap event::drain USR1
while :; do
  sleep 60 &
  wait $!
done
```

When `SIGUSR1` arrives, Bash runs `event::drain`, which reads every line of the log it hasn't seen yet, with `mapfile -s` to skip the ones it has, and calls each listener.

> [!NOTE]
> Bash only runs a trap when the current command finishes. If the loop were just `sleep 60`, an event could wait up to a minute. `wait` is different: a signal interrupts it straight away. So the loop runs `sleep` in the background and waits for it.

### Why the payload goes in a file

Signals carry no data at all, there are only two for our own use (`USR1` and `USR2`), and two of the same signal arriving close together can be merged into one. So the signal can't be the event. It just means "go and look", and the listener reads everything new since it last looked. Two merged signals still mean the listener looks once and finds both events.

## Broadcasting Events

An event is broadcast if it has a `broadcastOn` function, which is Laravel Bash's `ShouldBroadcast`:

```bash
OrderShipped::broadcastOn() {
  echo orders
}
```

See [Broadcasting](/docs/broadcasting). Every event and every listener that handles one is also broadcast on the `events` channel, so you can watch the doorbell ring on [Pulse](/pulse).
