Organizing Code for OTP Abstractions

Let’s learn how we can integrate our layers into projects that make OTP callbacks.

A growing number of Elixir projects are allowing library integration by making OTP callbacks, or something like them, directly available to developers. In the following few lessons, we’ll suggest how you might integrate our layers into those frameworks. We’ll cover the following:

  • Phoenix Channels

  • Phoenix LiveView

  • Scenic

Once we know how these work, we’ll have a pretty good idea of how to integrate with other callback-style frameworks.

Let’s go over a few clues that will help us recognize where the primary integration points might be for each section. Once we find those integration points, we’ll know how to tie it into the rest of the layers in our project. In each case, the key will be to find where each library exposes callbacks from within an OTP GenServer.

Understand callback-style libraries

If we want to use a simple mix project as a dependency, whether an OTP project or a simple library, we don’t care about the callback structure. Sometimes, though, we’ll want to replace the boundary layer in the chapter Isolating Process Machinery in a Boundary with one wired directly to the framework we’re using. The GenServer behavior has at least two pieces of functionality any framework needs to wrap:

A way to start a process

The GenServer calls these functions within process start machinery. The formal GenServer behavior has both a start_link function and an init function.

A way to process a callback

GenServers invoke these callbacks in the machinery that receives messages. The GenServer behavior has at least three interesting callbacks, including handle_call, handle_cast, and handle_info.

For convenience, we also wrapped our callbacks in functions, but don’t let that distract you. Startup and callbacks are the pieces we want to look for. Once we identify those pieces, then incorporating an event-based library is easy.


Get hands-on with 1200+ tech skills courses.