Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $9.99/month after trial. Cancel anytime.

Phoenix in Action
Phoenix in Action
Phoenix in Action
Ebook698 pages6 hours

Phoenix in Action

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Summary

Phoenix is a modern web framework built for the Elixir programming language. Elegant, fault-tolerant, and performant, Phoenix is as easy to use as Rails and as rock-solid as Elixir's Erlang-based foundation. Phoenix in Action builds on your existing web dev skills, teaching you the unique benefits of Phoenix along with just enough Elixir to get the job done.

Foreword by Sasa Juric, author of Elixir in Action, Second Edition.

Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.

About the Technology

Modern web applications need to be efficient to develop, lightning fast, and unfailingly reliable. Phoenix, a web framework for the Elixir programming language, delivers on all counts. Elegant and intuitive, Phoenix radically simplifies the dev process. Built for concurrency, Phoenix channels make short work of developing real-time applications. And as for reliability, Phoenix apps run on the battle-tested Erlang VM, so they're rock solid!

About the Book

Phoenix in Action is an example-based book that teaches you to build production-quality web apps. You'll handle business logic, database interactions, and app designs as you progressively create an online auction site. As you go, you'll build everything from the core components to the real-time user interactions where Phoenix really shines.

What's inside

  • Functional programming in a web environment
  • An introduction to Elixir
  • Database interactions with Ecto
  • Real-time communication with channels

About the Reader

For web developers familiar with a framework like Rails or ASP.NET. No experience with Elixir or Phoenix required.

About the Author

Geoffrey Lessel is a seasoned web developer who speaks and blogs about Elixir and Phoenix.

Table of Contents

    PART 1 - GETTING STARTED
  1. Ride the Phoenix
  2. Intro to Elixir
  3. A little Phoenix overview
  4. PART 2 - DIVING IN DEEP
  5. Phoenix is not your application
  6. Elixir application structure
  7. Bring in Phoenix
  8. Making changes with Ecto.Changeset
  9. Transforming data in your browser
  10. Plugs, assigns, and dealing with session data
  11. Associating records and accepting bids
  12. PART 3 - THOSE IMPORTANT EXTRAS
  13. Using Phoenix channels for real-time communication
  14. Building an API
  15. Testing in Elixir and Phoenix
LanguageEnglish
PublisherManning
Release dateApr 26, 2019
ISBN9781638356202
Phoenix in Action
Author

Geoffrey Lessel

Geoffrey Lessel is a seasoned web developer who speaks and blogs about Elixir and Phoenix.

Related to Phoenix in Action

Related ebooks

Software Development & Engineering For You

View More

Related articles

Reviews for Phoenix in Action

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Phoenix in Action - Geoffrey Lessel

    Copyright

    For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact

           Special Sales Department

           Manning Publications Co.

           20 Baldwin Road

           PO Box 761

           Shelter Island, NY 11964

           Email: 

    [email protected]

    ©2019 by Manning Publications Co. All rights reserved.

    No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

    Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

    Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

    Development editor: Kristen Watterson

    Technical development editor: Marius Butuc

    Review editor: Ivan Martinović

    Production editor: Deirdre Hiam

    Copy editor: Andy Carroll

    Proofreader: Katie Tennant

    Technical proofreader: Kumar Unnikrishnan

    Typesetter and cover designer: Marija Tudor

    ISBN 9781617295041

    Printed in the United States of America

    Brief Table of Contents

    Copyright

    Brief Table of Contents

    Table of Contents

    Foreword

    Preface

    Acknowledgments

    About this book

    About the author

    About the cover illustration

    1. Getting started

    Chapter 1. Ride the Phoenix

    Chapter 2. Intro to Elixir

    Chapter 3. A little Phoenix overview

    2. Diving in deep

    Chapter 4. Phoenix is not your application

    Chapter 5. Elixir application structure

    Chapter 6. Bring in Phoenix

    Chapter 7. Being persistent with a database

    Chapter 8. Making changes with Ecto.Changeset

    Chapter 9. Transforming data in your browser

    Chapter 10. Plugs, assigns, and dealing with session data

    Chapter 11. Associating records and accepting bids

    3. Those important extras

    Chapter 12. Using Phoenix channels for real-time communication

    Chapter 13. Building an API

    Chapter 14. Testing in Elixir and Phoenix

    A. Installing Elixir and Phoenix

    B. More Elixir resources

     The general flow of a request as it moves through Phoenix

    Index

    List of Figures

    List of Tables

    List of Listings

    Table of Contents

    Copyright

    Brief Table of Contents

    Table of Contents

    Foreword

    Preface

    Acknowledgments

    About this book

    About the author

    About the cover illustration

    1. Getting started

    Chapter 1. Ride the Phoenix

    1.1. What is Phoenix?

    1.2. Elixir and Phoenix vs. the alternatives

    1.2.1. Real-time communication

    1.2.2. Efficient, small processes

    1.2.3. Background computation

    1.2.4. Minimal hardware requirements, low-cost scaling

    1.2.5. It’s not all roses

    1.3. The power of Elixir

    1.3.1. Scalability

    1.3.2. Supervision trees

    1.3.3. Erlang VM

    1.3.4. Macro and metaprogramming support

    1.3.5. OTP

    1.4. Functional vs. object-oriented programming

    1.4.1. Overview of functional programming

    1.5. Keep reading

    Summary

    Chapter 2. Intro to Elixir

    2.1. The basics

    2.1.1. IEx

    2.1.2. Basic types

    2.1.3. A small detour into functions

    2.1.4. Data type details

    2.1.5. Back to modules and named functions

    2.1.6. alias

    2.1.7. import

    2.2. Other idiomatic Elixir language features

    2.2.1. The pipe operator

    2.2.2. Pattern matching

    2.2.3. Using IEx.Helpers.v/1

    Summary

    Chapter 3. A little Phoenix overview

    3.1. Follow the data

    3.1.1. The basics of a web request

    3.1.2. Endpoint

    3.1.3. Router

    3.1.4. Controller

    3.1.5. Views

    3.1.6. Templates

    3.2. Putting it all together

    Summary

    2. Diving in deep

    Chapter 4. Phoenix is not your application

    4.1. I thought this book was about Phoenix

    4.2. The first steps in building your application

    4.2.1. Defining an item

    4.2.2. Adding a fake database

    4.2.3. Getting an Item by id

    4.2.4. Getting an Item based on other information

    4.3. Next steps

    Summary

    Chapter 5. Elixir application structure

    5.1. Moving from a single file to an application

    5.1.1. Using Mix to create a new application

    5.1.2. Generating an auction umbrella application

    5.1.3. The magic mix.exs file

    5.2. Organizing, compiling, and running your new application

    5.2.1. Breaking apart the three modules

    5.2.2. Compile and run!

    5.2.3. Running the Auction application for the first time

    5.3. Using Hex to get external dependencies

    5.3.1. Pulling in your dependencies

    Summary

    Chapter 6. Bring in Phoenix

    6.1. Installing Phoenix on your system

    6.2. Creating a new Phoenix application

    6.2.1. Running your server for the first time

    6.3. Listing items from the fake repo

    6.3.1. Modifying the controller and template

    Summary

    Chapter 7. Being persistent with a database

    7.1. A quick intro to Ecto

    7.2. Configuring Ecto

    7.2.1. Using Ecto’s Mix tools to set up your database

    7.3. Preparing Auction to use the database

    7.3.1. Defining the Auction.Item schema

    7.3.2. Migrating the database

    7.3.3. Pointing the public interface to the new repo

    7.3.4. Instructing the application to supervise the database connection

    7.3.5. Testing it out

    7.4. Creating, retrieving, and deleting data in the database

    7.4.1. Inserting data

    7.4.2. Retrieving data

    7.4.3. Deleting data

    7.4.4. Updating data

    7.4.5. What about the website?

    Summary

    Chapter 8. Making changes with Ecto.Changeset

    8.1. Can’t I just ... update?

    8.1.1. A brief intro to changesets

    8.1.2. Creating a changeset for Auction.Item

    8.2. Now you can update!

    8.2.1. Adjusting the public interface for updating

    Summary

    Chapter 9. Transforming data in your browser

    9.1. Handling new routes in your application

    9.1.1. Adding a new route

    9.1.2. Adding a new controller

    9.1.3. Adding a new view

    9.1.4. Adding a new template

    9.2. Viewing the details of a single item

    9.2.1. Defining the show route and function

    9.2.2. Defining the show.html template

    9.2.3. Linking to individual items

    9.3. Creating items through web forms

    9.3.1. Defining the new and create routes

    9.3.2. Defining the new controller function

    9.3.3. Defining the new template

    9.3.4. Defining the create controller function

    9.4. Editing items through web forms

    9.4.1. Defining the edit and update routes

    9.4.2. Defining the edit controller function

    9.4.3. Defining the edit.html.eex template

    9.4.4. Defining AuctionWeb.ItemController.update/2

    Summary

    Chapter 10. Plugs, assigns, and dealing with session data

    10.1. Preparing your application for user registration

    10.1.1. Defining the Auction.User schema

    10.1.2. Creating a migration to create the users table

    10.1.3. Defining changesets for Auction.User

    10.1.4. Creating API functions in Auction

    10.1.5. User registration web flow

    10.2. Handling user login and sessions

    10.2.1. Creating the route, controller, view, and templates for logging in and out

    10.2.2. Implementing the dirty details of sessions and authentication

    10.3. Plugs

    10.4. Adding site navigation

    10.4.1. Implementing the log out function

    10.5. Restricting users from certain pages

    Summary

    Chapter 11. Associating records and accepting bids

    11.1. Creating bids

    11.2. Adding associations to the Auction.Bid schema

    11.2.1. A little detour into associations

    11.2.2. Creating a migration that describes the associations

    11.2.3. Creating a form to accept bids

    11.3. Using has_many with items and users

    11.3.1. Preloading and avoiding N+1 queries

    11.3.2. Preloading associations in the public interface module and controller

    11.3.3. Adding the list of bids to the view template

    11.4. Listing a user’s bids on their profile page

    11.4.1. Using Ecto.Query to construct database queries

    11.4.2. Making a view helper function global and using the bids assign

    11.4.3. Using Timex to format dates and times

    11.5. Some ideas for further improvement

    Summary

    3. Those important extras

    Chapter 12. Using Phoenix channels for real-time communication

    12.1. What are Phoenix channels?

    12.2. Connecting a user to a channel and a topic

    12.2.1. Handling topic join requests

    12.2.2. Getting the user’s browser to join a topic

    12.3. Sending real-time messages to a user

    12.3.1. Receiving messages in the user’s browser

    12.3.2. Configuring the channel to handle messages

    12.3.3. Sending your browser a message from IEx

    12.4. Updating all users when a new bid is made

    12.4.1. Refactoring the rendering of an item’s bids

    12.4.2. Modifying the controller to broadcast a message

    12.4.3. Handling the broadcasted HTML in the browser

    Summary

    Chapter 13. Building an API

    13.1. Scoping API requests to a new controller

    13.2. Creating the AuctionWeb.Api.ItemController controller and view

    13.3. Including related bid and user data

    Summary

    Chapter 14. Testing in Elixir and Phoenix

    14.1. An introduction to ExUnit

    14.1.1. Writing a first test

    14.2. Setting up tests for Ecto

    14.2.1. Configuring a new database

    14.2.2. Creating a sandbox and configuring Ecto to use it in tests

    14.2.3. Setting up the database before tests run

    14.2.4. Creating a Mix alias for use during test runs

    14.3. Testing Ecto queries in Auction

    14.3.1. Testing Auction.list_items/0

    14.3.2. Testing Auction.get_item/1

    14.3.3. Testing Auction.insert_item/1

    14.4. Simultaneously writing documentation and tests with doctests

    14.4.1. Writing function-level documentation

    14.4.2. Viewing documentation in IEx

    14.4.3. Viewing documentation with ExDoc

    14.4.4. Adding examples and doctests

    14.4.5. Module-level documentation

    14.5. Writing tests For Phoenix

    14.5.1. Testing that an item is added to the database on success

    14.5.2. Testing that you’re redirected to the new item on success

    14.5.3. Testing that no item is created on error

    14.5.4. Testing that the new item form is rendered on error

    14.5.5. The entire ItemControllerTest module

    14.6. What next?

    Summary

    A. Installing Elixir and Phoenix

    A.1. Installing Elixir

    A.1.1. macOS and Unix/Linux variants

    A.1.2. Windows

    A.1.3. From source

    A.1.4. Installing Erlang

    A.2. Installing Phoenix

    A.2.1. PostgreSQL

    A.2.2. Node.js

    B. More Elixir resources

    On the web

    Books

    Community

     The general flow of a request as it moves through Phoenix

    Index

    List of Figures

    List of Tables

    List of Listings

    Foreword

    As you’re holding this book, starting your journey into the world of Elixir and Phoenix, I’m very excited for you! You’re about to discover a technology stack that can help you start your projects very quickly and move forward at a steady pace. At the same time, the technology will help you deal with highly complex challenges at a large scale. With Elixir and Phoenix, you’ll get a combination of a simple-start technology and a long-run one, a perfect combination that was out of reach just a few years ago.

    In the summer of 2010, I started using Erlang, the technology that’s the foundation of Elixir and Phoenix. Back then, Erlang was one of the few available languages suitable for the challenge we were facing. Erlang made it simple for us to implement a real-time push server, requiring a surprisingly small amount of code. The initial prototype, which could manage tens of thousands of simultaneous users, required about 200 lines of code!

    Over the next few years, I developed a love-hate relationship with Erlang. I was blown away by its first-class support for massive concurrency, scalability, and fault-tolerance. Writing highly concurrent code never felt so easy and natural. Our system scaled beautifully, and it kept the impact of errors to a minimum, preserving most of the service at any point in time, self-healing as soon as possible. But at the same time, working with Erlang felt tedious in many ways, with basic tasks, such as creating a new project or deploying to production, requiring a lot of manual steps. The code itself seemed burdened with a lot of boilerplate, and the language made it difficult to flush that boilerplate out. Finally, the ecosystem was much smaller than it is today, which required reinventing a lot of wheels.

    I remember having mixed feelings about Erlang back then. I really felt (and I still do!) that it is the soundest foundation for building any sort of a backend side system (which includes any kind of a web server). However, the lack of tooling and libraries made the task of building such systems with Erlang harder than it should be. People used to joke that Erlang made hard things easy, but at the same time it made easy things hard.

    Things started improving with the arrival of Elixir, which, compared to Erlang, seemed more focused on developer productivity, shipping with simple-to-use tools, and promoting first-class documentation. In addition, as a more complex language, bringing to the table additional features such as metaprogramming and pluggable polymorphism via protocols, Elixir allowed me to be more expressive, better organize my code, and reduce boilerplate. And at the same time, targeting the same runtime and being semantically close to Erlang, Elixir could reap all the great benefits of Erlang, and seamlessly use everything from its ecosystem (standard library, OTP, third-party libraries, and tools).

    As the adoption of Elixir increased, its ecosystem expanded. The introduction of Plug and Ecto paved the way for the Phoenix framework, which finally got us to the point where we could quickly start building a typical web-facing CRUD, without needing to reinvent a bunch of wheels in the process. Phoenix quickly gained traction, and people started using it in production. As a result, the core team developers gathered a lot of feedback, which helped them evolve the tool further. Some original ideas were abandoned and some new ideas introduced, and currently Phoenix seems quite different from it’s early days, or even from the 1.0 release. But at this point, it feels that we’re past the initial development stages. The amount of deprecations and disrupting changes seems to decrease with each new version. It’s always hard to predict the future, but I don’t expect significant deprecations in future versions.

    Therefore, I feel that the time to start learning Phoenix has never been better. The framework is mature and stable, the community is large and helpful, the technology has been used in various systems, and many good patterns and practices have been established. And on top of all that, there are many learning resources available, such as this book.

    Back in early 2013, when I first started using Elixir, there were no books about it. Instead, I’d read the reference documentation and post questions to the mailing list, where most of the answers would be given by José Valim, who was pretty much the only qualified person to answer any Elixir-related question at the time. When Chris McCord first announced Phoenix, there wasn’t even a reference document available. Learning to work with Phoenix required a combination of trial and error, reading the Phoenix code, and asking around on mailing lists or IRC. This learning process had a certain charm, but it was definitely far from perfect. As a result, a lot of the early code written with Elixir and Phoenix was ridden with weird approaches and techniques. It took some time and a lot of strayed paths before the early adopters became familiar with these tools and understood how to use them properly.

    But you don’t have to go through the same trials and tribulations. By starting your Phoenix journey now, you can avoid the mistakes made by the early adopters, and immediately start learning about proper ways to use the tools. This is where I see the biggest value of Phoenix in Action. This book will teach you the mechanics of the technology, but more importantly, it will explain how to think in Phoenix, by discussing established patterns, practices, and approaches. In addition, by cleverly avoiding the trap of writing a big reference book of epic proportions and carefully choosing which topics to discuss, Geoffrey makes your bootstrap experience smooth and easy. You won’t learn everything there is to know about Elixir and Phoenix, but no book can do that for you anyway. What you will learn, though, are the most important pieces you’ll need in pretty much any web-facing Elixir system, regardless of its shape and size.

    This is why I’m really excited for you. For many of us, the learning road was long and winding, but you’ve arrived at the party at the perfect time. Having this great book to bring you into the exciting world of Elixir and Phoenix, you’re off to a good start, and your journey is about to become much more exciting. I wish you a lot of fun on that journey!

    —Saša Jurić, author of Elixir in Action

    Preface

    I remember when I created my first true website—it was called The U2 Shack, and, as the name suggests, it was a site dedicated to the band U2. This was back in 1998, and it was handwritten with Windows Notepad in straight HTML. The site was hosted on GeoCities and was part of a link ring. It took forever to update because it was all hardcoded HTML, but it was mine and I was proud of it.

    Fast forward about three years, and I was introduced to Perl and then PHP. I was amazed that the server could process variables given to it by the web browser and spit out custom-built HTML based on the user’s request. For example, one fun site I made in those early days was a word-search generator. The user could input a list of words they wanted to be in a puzzle, as well as the width and height and whether to allow some words to be hidden backwards. The server would take all this information, brute-force a custom word-search puzzle, and output it in HTML for the user to print.

    I happily developed sites with PHP for years, and then Ruby on Rails dropped. Like many developers of the time, I was amazed at a video of the Rails author creating a fully functional blog engine in 10 minutes. I was sold. Almost instantly, I switched over to learning Ruby and developing websites with Ruby on Rails. I had tolerated Perl and PHP but fell in love with Ruby in 2005. For over a decade, Ruby and Ruby on Rails were my tools of choice, and I still use them every day.

    However, in 2014, I heard rumblings of a new language called Elixir, by José Valim. José was a major contributor to Ruby on Rails (and is still listed as number five on the all-time contributor list), but he was feeling some of the shortcomings of the Ruby language (like memory usage and the difficulty of developing for parallel and distributed programs). I bought a book about Elixir that year and fell in love all over again.

    Also in 2014, Chris McCord began building the web framework known as Phoenix on top of Elixir. Phoenix version 1.0 was ultimately released in August of 2015, and its major features were real-time communications, productive tooling, and blazingly fast responses. It’s been quite a journey since the days of developing in straight HTML, but ever since I discovered Phoenix, every web project I start begins with mix phx.new.

    I’ve had the pleasure of speaking at multiple Elixir conferences over the years and blogging about Elixir, Phoenix, and Ecto at geoffreylessel.com. I now have the great pleasure of introducing you to Phoenix in this book. I sincerely hope that the topics presented in this book allow you to build amazing applications of your own. If you do, I’d love to hear about it at [email protected].

    Happy reading!

    Acknowledgments

    As with any creative endeavor, there were many ups and downs during the creation of this book. But regardless of my feelings during the process, there were a number of people rooting for me, without whom this project would have been doomed.

    First and foremost, I’d like to thank my family. Kelly, my work on this book meant more work for you as well. Without your help and support, I’d never have been able to reach the finish line. Although none of the words in this book are yours, you are my coauthor. I love you. Special acknowledgments go to Olivia, Max, and Calvin. You were very patient with me throughout the process, and a father couldn’t ask for better children. I love you and am proud of you.

    I also thank my parents, John and Carolyn, who let me mess around and test my curiosity on the family computer, growing up.

    Next, I’d like to thank Kevin Harreld and Kristen Watterson at Manning. You both made major editorial contributions during the project, and this book would be much harder to read if it weren’t for you. Your dedication to excellence has made Phoenix in Action a hundred times better than it would have been without your involvement. Beyond Kevin and Kristen, my thanks go to the whole team at Manning for development, marketing, and production support. Deirdre Hiam, Andy Carroll, Katie Tennant, and Nichole Beard, I see and feel the results of your efforts. When I started on this project, I didn’t realize how much support I would truly receive from the Manning team. Thank you.

    I would also like to thank the following people who all took the time to review and comment on the book: Alessandro Campeis, Amit Lamba, Andrew Courter, Arun Kumar, Fillipe Massuda, Grzegorz Bernas, Gustavo Filipe Ramos Gomes, Jay Kelkar, Jeff Smith, Joel Kotarski, Johan Mattisson, John Kasiewicz, Lane LaRue, Luis Miguel Cabezas Granado, Massimiliano Bertinetti, Noel Martin Llevares, Olaoluwa Oluro, Peter Sellars, Piotr Kopszak, Ryan Huber, Samuel Bosch, Victor Durán, and Vincent Theron.

    Thank you, Jeff Berg, Daniel Murphy, Jesse Anderson, Michael Chan, and all my coworkers at Planning Center, who continually asked how the book was coming along. Thank you, all the MEAP readers and reviewers who submitted comments, suggestions, critiques, and praise for the book as it was being written.

    Thank you, Chris McCord, José Valim, and all the Elixir and Phoenix contributors. You have created tools that are a joy to use and excellent documentation that sometimes made me feel like my words were superfluous.

    Finally, thank you, my readers! I hope you enjoy this book.

    About this book

    Who should read this book

    Phoenix in Action was written to help you learn the Phoenix framework from ground zero. We’ll start as if you have no knowledge of how the framework functions, and by the final chapter, you’ll have written a functioning auction site (in the spirit of eBay). The web application you’ll create isn’t going to be feature-complete, and it won’t win any awards for design, but what you’ll learn in this book will give you the tools to expand on the application and continue to build it. Or, if you’d rather, you can finally create that web application that’s been bouncing around in your head for months.

    Both beginner and experienced developers will find a home in this book. But if you’ve never written code before, this book won’t serve as an introduction to general programming. For those who’ve never written any Elixir, chapter 2 will give you an overview of the language and teach you just enough to get you going. As you progress through the book, I’ll introduce new techniques and ideas as you need them, and I’ll point out best practices when I can. Beyond that, I’ll remind you of things we’ve covered in previous chapters in order to solidify that knowledge.

    How this book is organized: a roadmap

    Phoenix in Action is divided into 3 parts that consist of 14 chapters.

    Part 1 covers the basics of Phoenix and Elixir and introduces the broad topics of programming in each:

    Chapter 1 introduces Phoenix and Elixir and discusses the benefits that each provides to today’s developer. There’s even a section that describes some of Elixir’s downsides and the reasons why it and Phoenix may not be the best choice for a particular project.

    Chapter 2 goes deeper into the basics of the Elixir programming language. Even if you’ve never seen a line of Elixir code, this chapter will provide you with enough of an overview that you can start developing with it. If you’re already well versed in Elixir, feel free to skip to chapter 3.

    Chapter 3 delves into the Phoenix framework. By following a web request all the way from the user typing a URL into a browser through the various parts of a Phoenix application, you’ll understand how Phoenix is organized and what each file is responsible for.

    In part 2, you’ll start developing a Phoenix application—an auction site in the spirit of eBay. This part will provide you with what you need to know to create interactive websites in Phoenix:

    Chapter 4 is where you’ll dust off the text editor and start writing some code. You’ll begin by creating a public interface for the data portion of your eventual website. You’ll learn why it’s important to keep the business logic of your application separate from the presentation of that data through Phoenix, and you’ll learn how to do so. By the end of this chapter, you’ll be able to send Elixir commands to your application and list and find auction items.

    Chapter 5 introduces the Mix tool and will teach you how to organize an Elixir application. You’ll move from the everything-in-a-single-file approach in chapter 4 to a legitimate Elixir umbrella application (don’t worry—we’ll cover what an umbrella is too). You’ll also bring external dependencies into the application to give it extra functionality.

    Chapter 6 brings Phoenix into the application. Previous chapters did the backend work of the business logic, but here you’ll use Phoenix to display auction items in a web browser.

    Chapter 7 introduces Ecto, an Elixir package that allows you to interact with databases. In previous chapters, all the data in your application was read-only and hardcoded. In this chapter, you’ll move on to actually storing and retrieving data to and from a real database.

    Chapter 8 takes the topic of database interactions to the next level by teaching you how to edit and update information in the database. Using Ecto changesets, we’ll also discuss how to validate and restrict what data gets to the database, to ensure that no junk gets through.

    Chapter 9 brings all the things you learned in previous chapters back into Phoenix. You’ll use forms in Phoenix to allow the user to create and update an auction item in their browser.

    Chapter 10 discusses using plugs to deal with a user’s session data. We’ll go over user registration, authenticating those users, allowing them to log in and out, and restricting users from areas where they shouldn’t be allowed.

    Chapter 11 is all about data relationships. In particular, an item belongs to a user, and a user can bid on an item. You’ll learn how to keep all those relationships in order, and you’ll create an interface allowing users to bid on items.

    Part 3 has chapters designed to take your application to the next level:

    Chapter 12 dives into real-time communication via Phoenix channels. This will allow real-time push updates to all users on an item’s detail page. You’ll enable the application to update the list of bids in real time for every logged-in user when a new bid is created.

    Chapter 13 demonstrates how to create a simple API boundary for your Phoenix application. You’ll respond to user requests with JSON that you’ll build in Phoenix.

    Chapter 14 provides an overview of testing and documentation. Both are very important in the Elixir world, and Elixir and Phoenix provide amazing tools out of the box, not only for testing your functions, but also for testing your documentation!

    About the code

    Every chapter in this book has code listings (though the code in chapter 1 is very rudimentary). All the code in the book, organized by chapter, can be found on GitHub at https://github.com/PhoenixInAction/phoenix-in-action. Each chapter directory contains a reference for how the code should look at the end of that chapter. For example, if you follow through all the code listings in chapter 10, your code will roughly match the ch10 directory in the GitHub repo.

    During the course of writing this book, Elixir went from version 1.6 to 1.8.0-rc.1, and Phoenix went from version 1.3 to 1.4. The Elixir code should work in any version from 1.5 through 1.8 (and beyond), but the listings were written in version 1.7. If you have a different version, your output may look a bit different than what’s shown in the book, but that shouldn’t affect the results in any way. All the code in the book is meant to be run with Phoenix version 1.4, and although the future beyond 1.4 is mostly unknown to me, it should run just fine with little modification for many versions.

    This book contains many examples of source code both in numbered listings and in-line with normal text. In both cases, code is formatted in a fixed-width font like this to distinguish it from ordinary text.

    In many cases, the original source code has been reformatted; I’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers ( ). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings to highlight important concepts.

    liveBook discussion forum

    Purchase of Phoenix in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://livebook.manning.com/#!/book/phoenix-in-action/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/#!/discussion.

    Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking him some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

    About the author

    Geoffrey Lessel is a developer with 20 years of experience. He’s seen the world of open source web development move from Perl scripts to PHP, to Ruby on Rails, to Elixir and Phoenix, and he has developed in each along the way. He loves to teach what he learns and has spoken at multiple Elixir conferences over the years. He blogs about Elixir and Phoenix at http://geoffreylessel.com.

    About the cover illustration

    The figure on the cover of Phoenix in Action is captioned A man from Ostrov, Dalmatia, Croatia. The illustration is taken from a reproduction of an album of Croatian traditional costumes from the mid-nineteenth century by Nikola Arsenović, published by the Ethnographic Museum in Split, Croatia, in 2003. The illustrations were obtained from a helpful librarian at the Ethnographic Museum in Split, itself situated in the Roman core of the medieval center of the town: the ruins of Emperor Diocletian’s retirement palace from around AD 304. The book includes finely colored illustrations of figures from different regions of Croatia, accompanied by descriptions of the costumes and of everyday life.

    Dress codes and lifestyles have changed over the last 200 years, and the diversity by region, so rich at the time, has faded away. It’s now hard to tell apart the inhabitants of different continents, let alone of different hamlets or towns separated by only a few miles. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of

    Enjoying the preview?
    Page 1 of 1