Book Image

Build Your Own Web Framework in Elixir

By : Aditya Iyengar
Book Image

Build Your Own Web Framework in Elixir

By: Aditya Iyengar

Overview of this book

Elixir's functional nature and metaprogramming capabilities make it an ideal language for building web frameworks, with Phoenix being the most ubiquitous framework in the Elixir ecosystem and a popular choice for companies seeking scalable web-based products. With an ever-increasing demand for Elixir engineers, developers can accelerate their careers by learning Elixir and the Phoenix web framework. With Build Your Own Web Framework in Elixir, you’ll start by exploring the fundamental concepts of web development using Elixir. You'll learn how to build a robust web server and create a router to direct incoming requests to the correct controller. Then, you'll learn to dispatch requests to controllers to respond with clean, semantic HTML, and explore the power of Domain-Specific Languages (DSL) and metaprogramming in Elixir. You'll develop a deep understanding of Elixir's unique syntax and semantics, allowing you to optimize your code for performance and maintainability. Finally, you'll discover how to effectively test each component of your application for accuracy and performance. By the end of this book, you'll have a thorough understanding of how Elixir components are implemented within Phoenix, and how to leverage its powerful features to build robust web applications.
Table of Contents (15 chapters)
1
Part 1: Web Server Fundamentals
4
Part 2: Router, Controller, and View
10
Part 3: DSL Design

Code injection using macros

We learned that we can use Code.eval_quoted/3 to dynamically add behavior to a module, but Elixir provides a cleaner and more consistent way of doing this, using macro.

Code.eval_quoted/3 allows us to inject code using a set of variable bindings and an environment. macro, on the other hand, allows us to define a set of quoted literals at the time of their compilation and evaluate the expressions, by simply invoking it like a function inside another module. A macro can be defined by using defmacro/2, which itself is a macro.

To understand the preceding distinction better, let us use macro to implement the same BehaviorInjector module and inject behavior in the TestSubject module:

behavior_injector.ex

defmodule BehaviorInjector do
  defmacro define_hello do
    quote do
      def hello, do: IO.puts "Hello world!"
    end
  end
end

In the preceding...