Chris Mccord, Bruce Tate, José Valim — «Programming Phoenix
Total Page:16
File Type:pdf, Size:1020Kb
Early Praise for Programming Phoenix Programming Phoenix is an excellent introduction to Phoenix. You are taken from the basics to a full-blown application that covers the MVC layers, real-time client- server communication, and fault-tolerant reliance on 3rd party services. All tested, and presented in a gradual and coherent way. You’ll be amazed at what you’ll be able to build following this book. ➤ Xavier Noria Rails Core Team I write Elixir for a living, and Programming Phoenix was exactly what I needed. It filled in the sticky details, like how to tie authentication into web applications and channels. It also showed me how to layer services with OTP. The experience of Chris and José makes all of the difference in the world. ➤ Eric Meadows-Jönsson Elixir Core Team A valuable introduction to the Phoenix framework. Many small details and tips from the creators of the language and the framework, and a leader in using Phoenix in production. ➤ Kosmas Chatzimichalis Software Engineer, Mach7x Programming Phoenix is mandatory reading for anyone looking to write web appli- cations in Elixir. Every few pages I found myself putting the book down so I could immediately apply something I’d learned in my existing Phoenix applications. More than merely teaching the mechanics of using the Phoenix framework, the authors have done a fantastic job imparting the underlying philosophy behind it. ➤ Adam Kittelson Principal Software Engineer, Brightcove Programming Phoenix Productive |> Reliable |> Fast Chris McCord Bruce Tate and José Valim The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at https://pragprog.com. The team that produced this book includes: Jacquelyn Carter (editor) Potomac Indexing, LLC (index) Eileen Cohen (copyedit) Gilson Graphics (layout) Janet Furlow (producer) For customer support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2016 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-145-2 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—April 2016 Contents Acknowledgments . ix 1. Introducing Phoenix . 1 Fast 2 Concurrent 3 Beautiful Code 4 Interactive 7 Reliable 8 Is This Book for You? 9 Online Resources 12 Part I — Building with Functional MVC 2. The Lay of the Land . 15 Simple Functions 15 Installing Your Development Environment 18 Creating a Throwaway Project 20 Building a Feature 21 Going Deeper: The Request Pipeline 27 Wrapping Up 36 3. Controllers, Views, and Templates . 37 The Controller 37 Creating Some Users 40 Building a Controller 43 Coding Views 45 Using Helpers 46 Showing a User 48 Wrapping Up 51 Contents • vi 4. Ecto and Changesets . 53 Understanding Ecto 53 Defining the User Schema and Migration 55 Using the Repository to Add Data 58 Building Forms 60 Creating Resources 64 Wrapping Up 68 5. Authenticating Users . 69 Preparing for Authentication 69 Managing Registration Changesets 70 Creating Users 73 The Anatomy of a Plug 74 Writing an Authentication Plug 78 Implementing Login and Logout 83 Presenting User Account Links 86 Wrapping Up 88 6. Generators and Relationships . 91 Using Generators 91 Building Relationships 99 Managing Related Data 101 Wrapping Up 104 7. Ecto Queries and Constraints . 107 Adding Categories 107 Diving Deeper into Ecto Queries 114 Constraints 120 Wrapping Up 127 8. Testing MVC . 129 Understanding ExUnit 130 Using Mix to Run Phoenix Tests 131 Integration Tests 134 Unit-Testing Plugs 141 Testing Views and Templates 147 Splitting Side Effects in Model Tests 148 Wrapping Up 153 Contents • vii Part II — Writing Interactive and Maintainable Applications 9. Watching Videos . 157 Watching Videos 157 Adding JavaScript 160 Creating Slugs 164 Wrapping Up 171 10. Using Channels . 173 The Channel 174 Phoenix Clients with ES6 175 Preparing Our Server for the Channel 177 Creating the Channel 180 Sending and Receiving Events 182 Socket Authentication 186 Persisting Annotations 189 Handling Disconnects 195 Wrapping Up 198 11. OTP . 199 Managing State with Processes 199 Building GenServers for OTP 202 Supervision Strategies 208 Designing an Information System with OTP 212 Building the Wolfram Info System 216 Wrapping Up 227 12. Observer and Umbrellas . 229 Introspecting with Observer 229 Using Umbrellas 231 Wrapping Up 238 13. Testing Channels and OTP . 239 Testing the Information System 239 Isolating Wolfram 245 Adding Tests to Channels 250 Authenticating a Test Socket 252 Communicating with a Test Channel 252 Wrapping Up 257 Contents • viii 14. What’s Next? . 259 Other Interesting Features 260 What’s Coming Next 264 Good Luck 266 Index . 267 Acknowledgments Most of this book is written in a collective voice, but acknowledgments are deep and personal things. For this chapter alone, we’ll speak some as a team but also in each of our individual voices. You’ll notice that Chris has more to say than the rest of us, and as the creator of Phoenix, it’s right and proper that he does so. As a team, we’d like to thank this production crew. It’s been the finest any of us have ever worked with. Potomac Indexing, LLC handled our indexing, Eileen Cohen did our copyedit, and Janet Furlow managed the endless pro- duction details. These contributions were invaluable, but we’d also like to single a couple out for deeper praise. Jackie Carter, our longtime friend and editor, has as much to say about the quality of this book as any of the authors on this team. Your voice is constant, and your gentle encouragement pushed us at the right times and in the right ways. Also, Dave Thomas did the layout and cover for this book, but he’s also served as a tireless advocate for Elixir and Phoenix and has shared many plates of Indian food with this team. Your friendship and guidance are always appreciated. We might not have had the opportunity to write this book without your tireless contributions. The next plate of Indian is on us. And we mean it. Our reviewers worked hard to provide excellent feedback, even though the code serving as the foundation for this book was constantly shifting. Bryan Weber, Eric Meadows-Jönsson, Colby Blaisdel, Adam Guyot, Adam Kittelson, Jason Stiebs, Ian Warshak, Xavier Noria, George Guimaraes, Carlos Antonio da Silva, Bernardo Chaves, Ian Dees, Vince Foley, Brian Hogan, and Lauro Caetano all did various levels of reviews for us. Xavier Noria stands out for providing extraordinary service while going through broken examples and also providing excellent feedback for the concepts in this book. Thanks also to the beta readers who did great work for us. report erratum • discuss Acknowledgments • x José Valim Elixir has been a labor of love and a project that has exceeded my wildest expectations. Elixir wouldn’t exist without the support of my partners at Plataformatec. They were the first to believe Elixir could make a dent in the world, and their investments in the community have helped Elixir grow with strength and grace. Getting this far wouldn’t be possible without the unconditional support of my wife, Małgosia. Most of Elixir was written on a small desk placed in the corner of our bedroom. Of all the corners in the world, I can’t imagine a better one. Finally, I want to thank my parents and friends for teaching me the lessons that still guide me on this journey. Bruce Tate I would like to thank my family as always, especially Maggie. You inspire me; you make bad days better and good days impossibly great. I couldn’t do any of this without you. Also, thanks to Paul Janowitz at icanmakeitbetter.com. While going through an acquisition, you allowed me research time to spend on projects like this one. We both believe that the world is a better place when we can give back to the projects that contribute to our success. Thanks for putting your money where your mouth is. Ian, your journey continues to inspire me. It’s been great having you in this community, and I can’t wait for the great things you’ll do here. Also, to the Elixir Mafia, molte grazie. You know who you are. Chris McCord First, I would like to thank José Valim for creating Elixir, for his contributions to Phoenix, and for building a community that has been such a pleasure to be a part of. It goes without saying that Phoenix wouldn’t be possible without his work on Elixir, but it goes deeper than that. He has my deepest gratitude for setting in motion my dream career, sharing his wisdom on running large open source projects, and being a helpful friend in between hectic releases.