Repository navigation
Events
Laravex's event system provides a simple observer implementation, allowing you to decouple various aspects of your application. The event dispatcher is an OTP GenServer running as Laravex.Events.Dispatcher. Listeners can be synchronous module functions or queued via the Queues.
Define your event-to-listener map in app/Providers/EventServiceProvider by implementing a listen/0 function that returns a map:
defmodule App.Providers.EventServiceProvider do
def listen do
%{
App.Events.UserRegistered => [
App.Listeners.SendWelcomeEmail,
App.Listeners.ProvisionAccount
],
App.Events.OrderShipped => [
App.Listeners.UpdateInventory
]
}
end
endOn boot (or when event:cache loads the cached map), each listener in the map is registered with the dispatcher automatically.
An event is any Elixir struct (or atom). The simplest form is a plain struct:
defmodule App.Events.UserRegistered do
defstruct [:user_id, :email]
endA listener is a module that exports a handle/1 function:
defmodule App.Listeners.SendWelcomeEmail do
def handle(%App.Events.UserRegistered{email: email}) do
App.Mail.WelcomeMail
|> Map.put(:to, email)
|> Laravex.Mail.Mailer.send()
end
endPass a struct to Laravex.Events.Dispatcher.dispatch/1, or an atom with an optional payload:
# Dispatch a struct event
Laravex.Events.Dispatcher.dispatch(%App.Events.UserRegistered{
user_id: user.id,
email: user.email
})
# Dispatch an atom event with a plain payload
Laravex.Events.Dispatcher.dispatch(App.Events.OrderShipped, %{order_id: 42})The dispatcher matches the event's module name against registered listeners and invokes each in turn. Synchronous listeners are called inline; queued listeners are pushed to the queue (see Queued Listeners below).
You can register anonymous function listeners or additional module listeners after boot:
Laravex.Events.Dispatcher.listen(App.Events.UserRegistered, fn event ->
IO.puts("User registered: #{event.email}")
end)
Laravex.Events.Dispatcher.listen(App.Events.OrderShipped, App.Listeners.NotifyAdmin)To defer a listener to the Queues, use the Laravex.Events.ShouldQueue macro:
defmodule App.Listeners.ProcessPodcast do
use Laravex.Events.ShouldQueue
def handle(event) do
# This runs inside a queue worker
App.Services.PodcastProcessor.process(event.podcast_id)
end
enduse Laravex.Events.ShouldQueue injects a should_queue?/0 function that returns true. When the dispatcher encounters a listener module for which should_queue?() is truthy, it pushes a Laravex.Events.CallQueuedListener job (which calls listener.handle(data)) to the queue instead of invoking the listener synchronously.
You can override the flag on a per-module basis:
defmodule App.Listeners.LogOnly do
use Laravex.Events.ShouldQueue, queue: false # run synchronously
def handle(event), do: Logger.info(inspect(event))
endThe event map from EventServiceProvider.listen/0 can be pre-compiled and stored to disk so the dispatcher doesn't re-read it on every boot.
# Write bootstrap/cache/events.term
./artisan event:cache
# Remove the cache file
./artisan event:clearThe cached file is an Erlang binary term at bootstrap/cache/events.term. On next boot, Laravex.Events.EventCache.load!/1 reads the file and re-registers all listeners.
./artisan event:listThis prints every event and its listeners — combining those from EventServiceProvider.listen/0 and any registered at runtime via Dispatcher.listen/2. Output is sorted alphabetically by event name:
App.Events.OrderShipped
⇂ App.Listeners.UpdateInventory
App.Events.UserRegistered
⇂ App.Listeners.ProvisionAccount
⇂ App.Listeners.SendWelcomeEmail
Retrieve the runtime listener map programmatically:
Laravex.Events.Dispatcher.listeners()
# => %{App.Events.UserRegistered => [...], ...}# Only dispatch when condition is truthy
Laravex.Events.Dispatcher.dispatch_if(post.published, :post_published, %{post: post})
# Only dispatch when condition is falsy
Laravex.Events.Dispatcher.dispatch_unless(post.draft, :post_published, %{post: post})# Calls each listener in turn; stops at the first non-nil return value
result = Laravex.Events.Dispatcher.until(:find_handler, %{key: "value"})Mirrors Laravel's Dispatcher::until. Useful when you want the first willing listener to handle the event and all subsequent listeners to be skipped.
- Queues — job queue powering queued listeners
- Broadcasting — broadcasting events to the client
-
Artisan-Console —
event:list,event:cache,event:clear,make:event,make:listener
Laravex — Laravel-faithful application skeleton & runtime for Elixir.
GitHub
·
Docs
·
Limitations
·
Laravel Docs
Not affiliated with Laravel LLC or the Elixir core team. Built to feel like Laravel on the BEAM.
- Home
- Installation
- Configuration
- Directory-Structure
- Request-Lifecycle
- Service-Container
- Service-Providers
- Deployment
- Routing
- Middleware
- CSRF-Protection
- Controllers
- Requests
- Responses
- Views
- Blade-Templates
- Asset-Bundling
- Session
- Validation
- Error-Handling
- Logging
- Artisan-Console
- Broadcasting
- Cache
- Collections
- Events
- File-Storage
- Helpers
- HTTP-Client
- Localization
- Notifications
- Pipeline
- Queues
- Rate-Limiting
- Strings
- Task-Scheduling