📅  最后修改于: 2023-12-03 14:45:09.700000             🧑  作者: Mango
Phoenix is a powerful web framework for building high-performance, real-time applications. One of its key features is the ability to easily create and manage data models through the use of contexts. In this guide, we'll explore the basics of creating a context in Phoenix.
A context in Phoenix is a module that encapsulates business logic and data access code for a particular domain. Each context is responsible for managing the data for a specific feature or set of features of your application. Contexts are used to keep your code organized, modular, and testable.
To create a Phoenix context, you can use the following command:
mix phx.gen.context <ContextName> <SchemaName> <MigrationName> [--no-context]
<ContextName>
is the name of the context module, in CamelCase format.<SchemaName>
is the name of the Ecto schema module, also in CamelCase format.<MigrationName>
is the name of the migration file, in snake_case format.--no-context
is an optional flag that tells Phoenix not to generate a context module.For example, if we wanted to create a context for managing users, we could run the following command:
mix phx.gen.context Accounts User users name:string email:string password_hash:string
This would generate a new context module named Accounts.User
along with an Ecto schema module named Accounts.User
and a migration file named 20211001123456_create_users.exs
.
A Phoenix context typically consists of the following components:
Here is an example of what a simple Phoenix context might look like:
defmodule MyApp.Accounts do
defmodule User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name, :string
field :email, :string
field :password_hash, :string
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :password])
|> validate_required([:name, :email, :password])
|> unique_constraint(:email)
end
def create_user(attrs) do
changeset(%User{}, attrs)
|> Repo.insert()
end
end
def list_users do
Repo.all(User)
end
def get_user(id) do
Repo.get(User, id)
end
def update_user(user, attrs) do
changeset(user, attrs)
|> Repo.update()
end
def delete_user(user) do
Repo.delete(user)
end
end
Phoenix contexts are a powerful tool for organizing your code and providing a clean separation between your business logic and your data access code. By breaking your application into small, modular pieces, you can reduce complexity, improve maintainability, and make your code more testable. With the mix phx.gen.context
command, creating a context in Phoenix is quick and easy.