moai-lang-elixir
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Elixir 1.17+ Development Specialist - Phoenix 1.7, LiveView, Ecto, OTP patterns, and functional programming.
Auto-Triggers: , files, , , Phoenix/LiveView discussions
.ex.exsmix.exsconfig/Core Capabilities:
- Elixir 1.17: Pattern matching, pipes, protocols, behaviours, macros
- Phoenix 1.7: Controllers, LiveView, Channels, PubSub, Verified Routes
- Ecto: Schemas, Changesets, Queries, Migrations, Multi
- OTP: GenServer, Supervisor, Agent, Task, Registry
- ExUnit: Testing with setup, describe, async
- Mix: Build tool, tasks, releases
- Oban: Background job processing
Elixir 1.17+开发专家 - Phoenix 1.7、LiveView、Ecto、OTP模式及函数式编程。
自动触发条件:、文件、、目录、Phoenix/LiveView相关讨论
.ex.exsmix.exsconfig/核心能力:
- Elixir 1.17:模式匹配、管道操作符、协议、行为、宏
- Phoenix 1.7:控制器、LiveView、Channels、PubSub、Verified Routes
- Ecto:Schema、Changesets、查询、迁移、Multi
- OTP:GenServer、Supervisor、Agent、Task、Registry
- ExUnit:使用setup、describe、async进行测试
- Mix:构建工具、任务、发布包
- Oban:后台任务处理
Quick Patterns
快速模式示例
Phoenix Controller: Define a module using MyAppWeb with :controller. Create alias for the context module like MyApp.Accounts. Define action functions like show taking conn and params map with destructured id. Fetch data using the context function with bang like get_user! and render the template passing the data as assigns.
For create actions, pattern match on the context result tuple. On ok tuple, use pipe operator to put_flash with success message and redirect using ~p sigil for verified routes. On error tuple with Ecto.Changeset, render the form template passing the changeset.
Ecto Schema with Changeset: Define a module using Ecto.Schema and importing Ecto.Changeset. Define the schema block with field declarations including types like :string and virtual fields. Create a changeset function taking the struct and attrs, using pipe operator to chain cast with the list of fields to cast, validate_required, validate_format with regex, validate_length with min option, and unique_constraint.
GenServer Pattern: Define a module using GenServer. Create start_link taking initial_value and calling GenServer.start_link with MODULE, initial_value, and name option. Define client API functions that call GenServer.call with MODULE and the message atom. Implement init callback returning ok tuple with state. Implement handle_call callbacks for each message, returning reply tuple with response and new state.
Phoenix控制器:使用MyAppWeb定义带:controller的模块。为上下文模块(如MyApp.Accounts)创建别名。定义动作函数(如show),接收conn和带有解构id的params映射。使用带感叹号的上下文函数(如get_user!)获取数据,并渲染模板将数据作为assigns传递。
对于创建动作,对上下文结果元组进行模式匹配。如果是ok元组,使用管道操作符调用put_flash添加成功消息,并使用~p符号重定向到Verified Routes。如果是包含Ecto.Changeset的error元组,渲染表单模板并传递该changeset。
带Changeset的Ecto Schema:使用Ecto.Schema定义模块并导入Ecto.Changeset。定义schema块,包含字段声明(包括:string等类型和虚拟字段)。创建changeset函数,接收结构体和attrs,使用管道操作符链式调用cast(传入要转换的字段列表)、validate_required、带正则的validate_format、带min选项的validate_length以及unique_constraint。
GenServer模式:使用GenServer定义模块。创建start_link函数,接收initial_value并调用GenServer.start_link,传入__MODULE__、initial_value和name选项。定义客户端API函数,调用GenServer.call传入__MODULE__和消息原子。实现init回调,返回包含状态的ok元组。为每个消息实现handle_call回调,返回包含响应和新状态的reply元组。
Implementation Guide (5 minutes)
实现指南(5分钟)
Elixir 1.17 Features
Elixir 1.17特性
Pattern Matching Advanced: Define function heads with pattern matching on map keys and types. Use guard clauses with when to add constraints like is_binary or byte_size checks. Add a catch-all clause returning error tuple for invalid inputs.
Pipe Operator with Error Handling: Use the with special form for chaining operations that may fail. Pattern match each step with left arrow, and on successful completion of all steps, return the final ok tuple. In the else block, handle error tuples by returning them unchanged.
Protocols for Polymorphism: Define a protocol with @doc and function specification using defprotocol. Implement the protocol for specific types using defimpl with for: option. Each implementation provides the specific behavior for that type.
高级模式匹配:定义函数头,对映射键和类型进行模式匹配。使用带when的守卫子句添加约束,如is_binary或byte_size检查。添加一个捕获所有情况的子句,返回错误元组以处理无效输入。
带错误处理的管道操作符:使用with特殊形式链式调用可能失败的操作。使用左箭头对每个步骤进行模式匹配,当所有步骤成功完成时,返回最终的ok元组。在else块中,直接返回错误元组以处理失败情况。
用于多态的协议:使用@doc和defprotocol定义协议及函数规范。使用带for:选项的defimpl为特定类型实现协议。每个实现为该类型提供特定行为。
Phoenix 1.7 Patterns
Phoenix 1.7模式
LiveView Component: Define a module using MyAppWeb with :live_view. Implement mount callback taking params, session, and socket, returning ok tuple with assigned state. Implement handle_event callback for user interactions, returning noreply tuple with updated socket using update helper. Implement render callback with assigns, using ~H sigil for HEEx templates with assigns accessed via @ prefix.
LiveView Form with Changesets: In mount, create initial changeset and assign using to_form helper. Implement validate event handler that creates changeset with :validate action and reassigns the form. Implement save event handler that calls context create function, on success using put_flash and push_navigate, on error reassigning the form with error changeset.
Phoenix Channels: Define a module using MyAppWeb with :channel. Implement join callback matching on topic pattern with angle brackets for dynamic segments. Use send with self() for after_join messages. Implement handle_info for server-side messages using push. Implement handle_in for client messages using broadcast! to send to all subscribers.
Verified Routes: Define routes in router.ex within scope blocks using live macro for LiveView routes. Use ~p sigil for verified routes in templates and controllers, with interpolation syntax for dynamic segments.
LiveView组件:使用MyAppWeb定义带:live_view的模块。实现mount回调,接收params、session和socket,返回包含已赋值状态的ok元组。实现handle_event回调处理用户交互,返回包含使用update助手更新后的socket的noreply元组。实现带assigns的render回调,使用~H符号编写HEEx模板,通过@前缀访问assigns。
带Changesets的LiveView表单:在mount中,创建初始changeset并使用to_form助手赋值。实现validate事件处理函数,创建带:validate动作的changeset并重新赋值表单。实现save事件处理函数,调用上下文创建函数,成功时使用put_flash和push_navigate,失败时重新赋值包含错误changeset的表单。
Phoenix Channels:使用MyAppWeb定义带:channel的模块。实现join回调,匹配带尖括号动态段的主题模式。使用send self()发送after_join消息。实现handle_info处理服务器端消息,使用push发送。实现handle_in处理客户端消息,使用broadcast!发送给所有订阅者。
Verified Routes:在router.ex的scope块中使用live宏定义LiveView路由。在模板和控制器中使用~p符号访问Verified Routes,使用插值语法处理动态段。
Ecto Patterns
Ecto模式
Multi for Transactions: Use Ecto.Multi.new() and pipe through operations using Ecto.Multi.update with name atoms and changeset functions. Use Ecto.Multi.insert with function callback when needing results from previous steps. Pipe final Multi to Repo.transaction() which returns ok or error tuple with named results.
Query Composition: Create a query module with composable query functions. Define a base function returning from expression. Create filter functions with default parameter for query, returning modified from expression with where clause. Chain functions with pipe operator before passing to Repo.all.
用于事务的Multi:使用Ecto.Multi.new(),并通过Ecto.Multi.update(传入名称原子和changeset函数)链式调用操作。当需要前一步结果时,使用带函数回调的Ecto.Multi.insert。将最终的Multi传递给Repo.transaction(),它会返回包含命名结果的ok或error元组。
查询组合:创建一个包含可组合查询函数的查询模块。定义一个返回from表达式的基础函数。创建带查询默认参数的过滤函数,返回添加了where子句的修改后的from表达式。在传递给Repo.all之前,使用管道操作符链式调用这些函数。
Advanced Implementation (10+ minutes)
高级实现(10分钟以上)
For comprehensive coverage including:
- Production deployment with releases
- Distributed systems with libcluster
- Advanced LiveView patterns (streams, components)
- OTP supervision trees and dynamic supervisors
- Telemetry and observability
- Security best practices
- CI/CD integration patterns
See:
- Advanced Patterns - Complete advanced patterns guide
如需全面了解以下内容:
- 使用发布包进行生产部署
- 基于libcluster的分布式系统
- 高级LiveView模式(流、组件)
- OTP监督树和动态监督者
- 遥测与可观测性
- 安全最佳实践
- CI/CD集成模式
请参阅:
- 高级模式 - 完整的高级模式指南
Context7 Library Mappings
Context7库映射
- /elixir-lang/elixir - Elixir language documentation
- /phoenixframework/phoenix - Phoenix web framework
- /phoenixframework/phoenix_live_view - LiveView real-time UI
- /elixir-ecto/ecto - Database wrapper and query language
- /sorentwo/oban - Background job processing
- /elixir-lang/elixir - Elixir语言文档
- /phoenixframework/phoenix - Phoenix Web框架
- /phoenixframework/phoenix_live_view - LiveView实时UI
- /elixir-ecto/ecto - 数据库包装器和查询语言
- /sorentwo/oban - 后台任务处理
Works Well With
协同工具
- - REST API and microservices architecture
moai-domain-backend - - SQL patterns and query optimization
moai-domain-database - - DDD and testing strategies
moai-workflow-testing - - AI-powered debugging
moai-essentials-debug - - Deployment and infrastructure
moai-platform-deploy
- - REST API和微服务架构
moai-domain-backend - - SQL模式和查询优化
moai-domain-database - - DDD和测试策略
moai-workflow-testing - - AI驱动的调试
moai-essentials-debug - - 部署与基础设施
moai-platform-deploy
Troubleshooting
故障排除
Common Issues:
Elixir Version Check: Run elixir --version to verify 1.17+ and mix --version for Mix build tool version.
Dependency Issues: Run mix deps.get to fetch dependencies, mix deps.compile to compile them, and mix clean to remove build artifacts.
Database Migrations: Run mix ecto.create to create database, mix ecto.migrate to run migrations, and mix ecto.rollback to rollback last migration.
Phoenix Server: Run mix phx.server to start the server, iex -S mix phx.server to start with IEx shell, and MIX_ENV=prod mix release to build production release.
LiveView Not Loading:
- Check websocket connection in browser developer console
- Verify endpoint configuration includes websocket transport
- Ensure Phoenix.LiveView is listed in mix.exs dependencies
Last Updated: 2026-01-11
Status: Active (v1.1.0)
常见问题:
Elixir版本检查:运行验证1.17+版本,运行检查Mix构建工具版本。
elixir --versionmix --version依赖问题:运行获取依赖,编译依赖,清除构建产物。
mix deps.getmix deps.compilemix clean数据库迁移:运行创建数据库,执行迁移,回滚上一次迁移。
mix ecto.createmix ecto.migratemix ecto.rollbackPhoenix服务器:运行启动服务器,启动带IEx shell的服务器,构建生产环境发布包。
mix phx.serveriex -S mix phx.serverMIX_ENV=prod mix releaseLiveView无法加载:
- 在浏览器开发者控制台中检查WebSocket连接
- 验证端点配置包含WebSocket传输
- 确保Phoenix.LiveView已列在mix.exs依赖中
最后更新:2026-01-11
状态:活跃(v1.1.0)