The most important directory: lib

Now we'll move on to the real meat of our Phoenix application: lib. Lib is where our application lives. By default, our Phoenix application is broken into two separate ideas. Using the application name of Sampler as an example, we will see two directories: lib/sampler and lib/sampler_web. The idea behind this is that every web application in Phoenix has at least two separate applications that work together to get the job done. The first is divorced from the idea of anything web-related, so there are no controllers or templates, JSON, or anything similar. One of the most common patterns that you’ll see here is all of your database-specific Ecto logic through contexts and schemas.

A context is a collection or boundary of domain-specific logic. For example, if you have users and organizations in your project, you may have a unifying context to those separate schemas called something like Accounts.

A Schema, on the other hand, is the one-to-one mapping of a database table to an application concept. Schemas need to be separated from the functionality of your code and used strictly to describe the shape of the data; this keeps your code pure from side-effects and helps make your code significantly easier to test in the long run.

Finally, we have lib/sampler_web. This is where all of the Phoenix-specific work gets done, so everything related to controller logic, templates, or views goes here in the appropriate sub-directory. Channel logic also falls underneath this particular design pattern. This is also where the endpoint.ex file lives, which defines how Plug constructs the Phoenix response to browser/API consumer/etc. It also determines how requests are parsed and how information is passed along to the Phoenix router.

Speaking of the router, our Phoenix router.ex file also lives here (again, because this is Phoenix-specific logic rather than the overarching common application functionality). This is where we will set up all of the rules to describe how to communicate between the browser and Phoenix's controllers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset