Przejdź do głównej zawartości

Elixir & Phoenix Patterns

Ta treść nie jest jeszcze dostępna w Twoim języku.

Master Elixir and Phoenix development with Cursor IDE and Claude Code. These patterns cover functional programming, OTP principles, LiveView, concurrent systems, and the unique features that make Elixir perfect for building fault-tolerant, real-time applications.

  1. Open Cursor in your workspace
  2. Launch Agent mode (Cmd/Ctrl + I)
  3. Prompt: “Create an Elixir Phoenix project with:
    • Phoenix 1.7+ with LiveView
    • Ecto for database
    • Tailwind CSS
    • Authentication system
    • Docker configuration
    • Test setup with ExUnit”
  4. Agent handles mix commands and setup
# Phoenix architecture prompt:
"Set up Phoenix application with:
- Contexts for domain logic
- LiveView for real-time UI
- PubSub for messaging
- Ecto schemas and migrations
- Background jobs with Oban
- Telemetry for monitoring"
# Generated structure:
lib/
my_app/
accounts/ # Context
catalog/ # Context
mailer/
repo.ex
my_app_web/
live/
controllers/
components/
router.ex
# LiveView component prompt:
"Create a LiveView for real-time dashboard with:
- Multiple chart components
- Live data updates via PubSub
- User interactions
- Optimistic UI updates
- Error recovery"
# Real-time features prompt:
"Implement real-time chat with:
- Phoenix Channels
- Presence tracking
- Message history
- Typing indicators
- Read receipts
- Push notifications"

LiveView Best Practices

AI can help with:

  • Optimizing assigns updates
  • Reducing data over wire
  • Client-side hooks
  • JavaScript interop
  • SEO considerations
# GenServer prompt:
"Create GenServer for:
- Rate limiting service
- State persistence
- Crash recovery
- Dynamic supervision
- Telemetry events
- Backpressure handling"
  1. Design Supervision: “Create supervision tree for payment processing”
  2. Implement Workers: “Add GenServer workers with restart strategies”
  3. Add Dynamic Supervisors: “Implement dynamic worker pools”
  4. Monitor Health: “Add telemetry and health checks”
# Ecto schema prompt:
"Design Ecto schemas for e-commerce:
- Multi-tenant architecture
- Polymorphic associations
- Soft deletes
- Audit logging
- Full-text search
- Database views"

Complex Queries

# Prompt: "Create Ecto query with:
# - Window functions
# - CTEs
# - Lateral joins
# - Aggregations"

Performance

# Prompt: "Optimize queries with:
# - Preloading strategies
# - Batch loading
# - Query fragments
# - Raw SQL when needed"
# Concurrency patterns prompt:
"Implement concurrent system for:
- Parallel data processing
- Task supervision
- Flow-based programming
- GenStage pipelines
- Broadway integration
- Back-pressure handling"
# Actor pattern:
"Design actor system with:
- Message protocols
- State machines
- Event sourcing
- Process registry
- Distributed actors"
# Test suite prompt:
"Create test suite with:
- Unit tests with ExUnit
- LiveView testing
- Channel testing
- Integration tests
- Property-based tests with StreamData
- Mox for mocking"
  1. Factory Setup: “Create test factories with ExMachina”
  2. Async Tests: “Configure async test execution”
  3. Database Sandboxing: “Set up Ecto sandbox mode”
  4. Coverage: “Add test coverage reporting”
# Auth system prompt:
"Implement authentication with:
- Pow or Guardian
- Multi-factor auth
- OAuth providers
- Session management
- Password policies
- Account lockout"

Security Checklist

AI can implement:

  • CSRF protection
  • Content Security Policy
  • Rate limiting
  • Input sanitization
  • SQL injection prevention
  • XSS protection
# GraphQL API prompt:
"Create GraphQL API with Absinthe:
- Schema design
- Resolvers with dataloader
- Subscriptions
- Authentication middleware
- Error handling
- Schema stitching"
# REST API design:
"Create JSON API with:
- Resource controllers
- Pagination
- Filtering
- API versioning
- OpenAPI docs"
# Performance optimization:
"Optimize Phoenix app for:
- Response time reduction
- Memory usage
- Database query optimization
- Caching strategies
- CDN integration
- Load testing"

ETS Caching

# Prompt: "Implement ETS cache:
# - TTL support
# - Cache warming
# - Invalidation
# - Memory limits"

Redis Integration

# Prompt: "Add Redis caching:
# - Connection pooling
# - Pub/sub support
# - Distributed cache
# - Cache aside pattern"
# Deployment prompt:
"Set up deployment with:
- Elixir releases
- Config providers
- Runtime configuration
- Health checks
- Rolling updates
- Kubernetes manifests"
  1. Build Release: “Configure mix release with Docker”
  2. Database Migrations: “Set up release migrations”
  3. Monitoring: “Add AppSignal or Telemetry”
  4. Scaling: “Configure clustering and service discovery”
# Distributed Elixir prompt:
"Implement distributed system with:
- libcluster for discovery
- Global process registry
- Distributed PubSub
- CRDTs for state
- Split-brain handling
- Network partitions"
# Event sourcing implementation:
"Create event-sourced system with:
- Commanded framework
- Event store
- Projections
- Process managers
- Saga orchestration
- Snapshot strategies"
# Structure prompts like:
"Create [module/function] in Elixir that:
- Follows OTP principles
- Handles these failure cases: [list]
- Includes @spec and @doc
- Has property-based tests
- Uses pattern matching effectively"
# Macro development:
"Create macro for:
- DSL implementation
- Compile-time validation
- Code generation
- AST manipulation
- Hygiene considerations"
# NIF/Port integration:
"Implement native integration:
- Rustler for NIFs
- Error handling
- Resource management
- Async NIFs
- Port drivers"

Avoid These Issues

When using AI for Elixir:

  • Don’t ignore OTP principles
  • Avoid mutable state patterns
  • Remember processes are cheap
  • Use supervisors appropriately
  • Test concurrent code thoroughly