- Phoenix Web Development
- Brandon Richey
- 325字
- 2021-08-27 18:28:29
Understanding the role of contexts
We talked a little bit about the sorts of issues that would lead us to want to control how our code is used and written since we don't want maintenance to become a giant hassle for us in the future. Therefore, let's instead simplify our lives by providing a single interface for related schemas and database operations.
Contexts fill that void by providing that unified interface, typically providing human-readable functions that allow the fetching, inserting, updating, and deleting of data. It can also do other database-specific operations that may be difficult to figure out ownership of (for example, should adding a new option to a poll live on the Poll or live on the schema? The correct answer is: neither!).
Overall, the end goal is that when someone else is working on our codebase (or, when we're working on this same codebase six months later and can't remember any of the decisions or code structure rules we originally laid out), we have a very simple way to interact with some of the more complicated parts of most applications. We provide simple and human-readable function names and control usage/interfaces for modifying or otherwise dealing with that data. This code used to just get shoved into helper modules scattered throughout your codebase or, even worse, littered your controller files with tons of non-controller-specific code. This code was hard to test, hard to track, and if you were working with a tight deadline on something, there was a good chance that you'd end up duplicating that code frequently instead of making sure the code was testable, maintainable, and otherwise useful.
Every context should have some helpers imported into it and aliased, but there's no special macro magic going on here. It's basically just a handy module that the application can use! It should also follow a simple naming definition. Since we created our context directory as lib/vocial/votes, we'll create lib/vocial/votes/votes.ex as our context!