# 5 รูปแบบสถาปัตยกรรมสำคัญ ที่ใช้ในการออกแบบระบบซอฟต์แวร์ทั่วไป

---

## 🏗️ ไฟล์ที่ 1: Layered Architecture (wk06-layer-arch.md)

### 📝 บรรยายไฟล์

**Layered Architecture** คือรูปแบบสถาปัตยกรรมที่หารแอปพลิเคชันออกเป็น **4 ชั้น** ที่วางซ้อนกันอย่างเป็นระบบ

### 🎯 ความสำคัญ

1. **Simple & Easy** - เข้าใจง่ายสำหรับผู้เริ่มต้น
2. **Proven Pattern** - ใช้มานานแล้ว ในหลายโปรเจคสำเร็จ
3. **Team Organization** - ทีมขนาดเล็ก (3-10 คน) จัดการได้ดี

### 🏛️ 4 ชั้นหลัก

#### ชั้นที่ 1: Presentation Layer (ผู้นำเสนอ)

```
หน้าที่: รับ request จาก client และส่ง response กลับ
ตัวอย่าง:
  - Controllers (เส้นทางจัดการ)
  - Routes (กำหนดเส้นทาง)
  - Middleware (ตรวจสอบ)
  - Error handlers (จัดการข้อผิดพลาด)

ไม่ควร:
  - ❌ เก็บข้อมูลไว้ในชั้นนี้
  - ❌ เขียน business logic ในชั้นนี้
```

#### ชั้นที่ 2: Business Logic Layer (ตรรกะธุรกิจ)

```
หน้าที่: ประมวลผล, ตรวจสอบกฎธุรกิจ, คำนวณ
ตัวอย่าง:
  - Services (บริการหลัก)
  - Validations (ตรวจสอบ)
  - Business rules (กฎธุรกิจ)
  - Calculations (คำนวณ)

สำคัญ:
  - ✓ ที่สุด pure business logic
  - ✓ ตัดสินใจหลัก
  - ✓ ไม่รู้เกี่ยว Database
  - ✓ ไม่รู้เกี่ยว UI
```

#### ชั้นที่ 3: Data Access Layer (เข้าถึงข้อมูล)

```
หน้าที่: Query database, map objects, cache
ตัวอย่าง:
  - Repositories (ที่เก็บข้อมูล)
  - ORM operations (แมพข้อมูล)
  - Database queries (สอบถาม)
  - Cache management (จัดการแคช)

ระดับ:
  - ✓ Abstraction of database
  - ✓ สามารถเปลี่ยน DB ได้ง่าย
```

#### ชั้นที่ 4: Database Layer (ฐานข้อมูล)

```
หน้าที่: เก็บข้อมูล, ความสัมพันธ์, Constraints
ตัวอย่าง:
  - MySQL / PostgreSQL
  - Tables (ตาราง)
  - Relationships (ความสัมพันธ์)
  - Indexes (ดัชนี)
  - Stored Procedures (ขั้นตอนเก็บ)
```

### 🔄 Request Flow (ไหลของ Request)

```
1. Browser → POST /users
   ↓
2. Presentation Layer (UserController)
   - รับ request
   - แยก data จาก body
   - เรียก UserService
   ↓
3. Business Logic Layer (UserService)
   - ตรวจสอบ email ถูกต้องหรือไม่
   - ตรวจสอบ user มีอยู่แล้วหรือไม่
   - Hash password
   - เรียก UserRepository
   ↓
4. Data Access Layer (UserRepository)
   - สร้าง SQL query
   - บันทึกลง database
   ↓
5. Database
   - INSERT user
   - Return inserted user
   ↓
6. Return to Service
   - Service return user
   ↓
7. Return to Controller
   - Controller create JSON response
   ↓
8. Browser
   - Render response
```

### ✅ ข้อดี

```
1. Simple & Easy
   - เข้าใจง่าย
   - ทำได้เร็ว

2. Organization
   - Code ที่ถูกแบ่งออก
   - ง่ายหาจุด bug

3. Reusability
   - Services สามารถ reuse
   - Repositories สามารถ reuse

4. Testing
   - Test layer by layer
   - Mock ได้ง่าย

5. Team
   - Clear role division
   - ทีมเล็กจัดการได้
```

### ❌ ข้อเสีย

```
1. Monolithic
   - ทั้งระบบ 1 deployment
   - ถ้า feature หนึ่งมีปัญหา ทั้งระบบ down

2. Scalability
   - Scale ได้เฉพาะระบบทั้งหมด
   - ไม่สามารถ scale feature เดียว

3. Database Bottleneck
   - Database อาจเป็นจุดเสี่ย
   - ทั้งระบบ query database เดียว

4. Limited Tech Diversity
   - ต้องใช้ tech stack เดียว
   - ทั้งระบบ Node.js หรือทั้งระบบ Java
```

### 🤔 ใช้เมื่อใด

```
✅ ใช้เมื่อ:
- โครงการขนาด Small-Medium (ไม่ใหญ่มาก)
- ทีม 3-10 คน
- Business logic ไม่ซับซ้อนมาก
- ต้องออกแบบด่วน

❌ ไม่ใช้เมื่อ:
- ทีม 100+ คน
- ต้องมี 10 services อิสระ
- ต้องใช้ Java บางส่วน Python บางส่วน
- ระบบได้รับ traffic มากมาย
```

### 💻 Code Example ที่สำคัญ

```javascript
// Controller (Presentation)
app.post('/users', async (req, res) => {
  const user = await userService.createUser(req.body);
  res.status(201).json(user);
});

// Service (Business Logic)
class UserService {
  async createUser(data) {
    // ตรวจสอบ
    if (!this.isValidEmail(data.email)) {
      throw new Error('Email ไม่ถูก');
    }
    // เรียก Repository
    return await userRepository.save(data);
  }
}

// Repository (Data Access)
class UserRepository {
  async save(user) {
    const [result] = await db.query(
      'INSERT INTO users (...) VALUES (...)',
      [...]
    );
    return result;
  }
}
```

### 📊 Real-world Examples

```
1. E-Commerce Website
   - Controller: ProductController, OrderController
   - Service: OrderService, PaymentService
   - Repository: ProductRepository, OrderRepository
   - Database: MySQL

2. Banking System
   - Service: AccountService, TransferService
   - Repository: AccountRepository
   - Database: PostgreSQL (สำคัญเรื่อง security)

3. Social Media (ตอนเริ่มแรก)
   - Service: PostService, CommentService
   - Database: MySQL
   - Cached with Redis
```

### 🎓 สรุป Layered Architecture

```
✨ Key Points:
1. 4 ชั้น = Presentation, Business, Data, Database
2. Request ไหลจากบนลงล่าง
3. Easy to understand & maintain
4. Good for small-medium teams
5. Simple to deploy
6. Limitations: Monolithic, hard to scale
```

---

## 🚀 ไฟล์ที่ 2: Microservices Architecture (wk06-micro-services-arch.md)

### 📝 บรรยายไฟล์

**Microservices Architecture** คือการแบ่งระบบขนาดใหญ่ออกเป็น **services ขนาดเล็กอิสระ** โดยแต่ละ service:

- มี database ของตัวเอง
- Deploy อิสระ
- ติดต่อกันผ่าน APIs
- ทีมแต่ละคน manage service เอง

### 🎯 ความสำคัญ

1. **Scalability** - Scale แต่ละ service ตามต้องการ
2. **Independence** - Develop/Deploy อิสระ
3. **Resilience** - Service หนึ่ง down ไม่ทำให้ทั้งระบบ down
4. **Technology Choice** - แต่ละ service เลือก tech ตัวเอง

### 🏢 โครงสร้าง Microservices

```
┌─────────────────────────────────────┐
│       API Gateway                   │
│  - Routing                          │
│  - Authentication                   │
│  - Rate limiting                    │
└─────────────────────────────────────┘
         ↓↑
    ┌────┴────┬───────────┬────────────┐
    ↓         ↓           ↓            ↓
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
│ User   │ │Product │ │ Order  │ │Payment │
│Service │ │Service │ │Service │ │Service │
│        │ │        │ │        │ │        │
├────────┤ ├────────┤ ├────────┤ ├────────┤
│User DB │ │Product │ │Order DB│ │Payment │
│        │ │ DB     │ │        │ │ DB     │
└────────┘ └────────┘ └────────┘ └────────┘

↓ → ↑ ← ↓ → ↑

┌─────────────────────────────────────┐
│   Message Bus / Event Broker        │
│   (RabbitMQ, Kafka, AWS SNS/SQS)   │
└─────────────────────────────────────┘

┌─────────────────────────────────────┐
│   Service Registry & Discovery      │
│   (Consul, Eureka, Kubernetes)      │
└─────────────────────────────────────┘
```

### 📋 Services ในระบบ

```
1. User Service
   - สมัครสมาชิก (Register)
   - เข้าสู่ระบบ (Login)
   - จัดการโปรไฟล์
   - Database: users_db

2. Product Service
   - สินค้า, ค้นหา, ตัวกรอง
   - ความเห็นและการให้คะแนน
   - Inventory levels
   - Database: products_db

3. Order Service
   - สร้างคำสั่ง
   - ติดตามคำสั่ง
   - ยกเลิกคำสั่ง
   - Database: orders_db

4. Payment Service
   - ประมวลผลการชำระเงิน
   - Refunds
   - Database: payments_db

5. Notification Service
   - ส่ง Email
   - ส่ง SMS
   - ส่ง Push notifications
```

### 🔄 Communication Patterns

#### 1. Synchronous (REST APIs)

```javascript
// Order Service เรียก User Service
const user = await axios.get("http://user-service/users/123");
// Pros: Simple, Real-time
// Cons: Slower, Dependency
```

#### 2. Asynchronous (Message Queue)

```javascript
// Order Service publish event
await kafka.producer.send({
  topic: "order-created",
  messages: [{ value: JSON.stringify(event) }],
});

// Notification Service listen
await consumer.run({
  eachMessage: async (event) => {
    await sendEmail(event);
  },
});
// Pros: Decoupled, Fast
// Cons: Eventually consistent
```

### 📊 Saga Pattern (Distributed Transaction)

```
Order Created Event
    ↓
Inventory Service
  ✓ Reserve items
    ↓
Payment Service
  ✓ Process payment
    ↓
Notification Service
  ✓ Send email
    ↓
✅ Order Complete

ถ้า Payment fail:
  - Publish "Payment Failed"
  - Inventory Service: Release items
  - Order Service: Update status to failed
```

### ✅ ข้อดี Microservices

```
1. Independent Scaling
   - Scale User Service 10x
   - Scale Order Service 2x
   - Scale ตามความต้องการจริง

2. Independent Deployment
   - Deploy User Service ไม่ต้อง deploy อื่น
   - ลดความเสี่ยง
   - ทำได้เร็ว

3. Technology Diversity
   - Service A: Node.js
   - Service B: Java
   - Service C: Python
   - ใช้เครื่องมือดีที่สุดสำหรับแต่ละงาน

4. Fault Isolation
   - Payment Service down
   - User Service ยังทำงาน
   - Order Service ยังทำงาน

5. Team Independence
   - ทีม A: User Service
   - ทีม B: Order Service
   - ทีม C: Payment Service
   - ทำงาน parallel ได้

6. Faster Development
   - ทีมเล็ก, scope ชัดเจน
   - Deploy เร็ว
   - Iterate เร็ว
```

### ❌ ข้อเสีย Microservices

```
1. Complexity
   - Network latency (ช้า)
   - Distributed transactions (ยาก)
   - Monitoring ซับซ้อน

2. Operational Overhead
   - ต้องเพิ่มทีม DevOps
   - Infrastructure ที่ซับซ้อน
   - Kubernetes, Docker, etc.

3. Testing
   - Integration testing ยาก
   - End-to-end testing ยาก

4. Data Consistency
   - Eventual consistency challenges
   - Data ไม่ consistent ชั่วขณะหนึ่ง

5. Deployment Complexity
   - Deploy 10 services (แทนที่ 1)
   - More infrastructure

6. Cost
   - Infrastructure cost มากขึ้น
   - ต้องเพิ่มทีม
```

### 🤔 ใช้เมื่อใด

```
✅ ใช้เมื่อ:
- ทีม 50-1000+ คน
- โครงการใหญ่มาก
- ต้อง scale features เดี่ยว
- ต้องใช้ tech stacks ต่างกัน
- Long-term project
- Enterprise application

❌ ไม่ใช้เมื่อ:
- ทีม < 20 คน
- โครงการเล็ก
- Business logic ไม่ซับซ้อน
- DevOps expertise ไม่มี
- การพัฒนาต้องเร็วมาก
```

### 💻 Code Example

```javascript
// User Service (Node.js)
app.post('/users', async (req, res) => {
  const user = await userService.create(req.body);
  // Publish event
  await eventBus.publish('user.created', user);
  res.status(201).json(user);
});

// Order Service (Java)
// Listen to user.created event
@Subscribe
public void onUserCreated(UserCreatedEvent event) {
  // Validate user exists
  // Create order
}

// Payment Service (Python)
# Listen to order.created
@app.route('/webhooks/order-created', methods=['POST'])
def on_order_created():
    event = request.json
    process_payment(event)
    return {'status': 'ok'}
```

### 📊 Real-world Examples

```
1. Netflix (Microservices at Scale)
   - 100,000+ microservices
   - Eureka (Service Discovery)
   - Hystrix (Circuit Breaker)
   - Chaos Engineering

2. Uber (Real-time Microservices)
   - Rider Service
   - Driver Service
   - Matching Service
   - Location Tracking Service
   - Real-time notifications

3. Amazon (Birth of Microservices)
   - Started: Monolith
   - Problem: Can't scale teams
   - Solution: Microservices
   - Result: Each team owns service
```

### 🎓 สรุป Microservices

```
✨ Key Points:
1. Services ขนาดเล็กอิสระ
2. Database per service
3. Deploy independent
4. Communicate via APIs
5. Scale each service separately
6. Good for: Large teams, complex projects
7. Bad for: Small projects, simple logic
```

---

## ⚡ ไฟล์ที่ 3: Event-Driven Architecture (wk06-event-driven-arch.md)

### 📝 บรรยายไฟล์

**Event-Driven Architecture** คือการออกแบบระบบโดย components ติดต่อกันผ่าน **events** (เหตุการณ์) แทนที่จะเรียกโดยตรง

### 🎯 ความสำคัญ

1. **Loose Coupling** - ส่วนต่างๆ ไม่รู้กันเอง
2. **Real-time Processing** - React ต่ออเหตุการณ์ทันที
3. **Scalability** - ง่ายต่อการเพิ่ม consumers
4. **Event History** - เก็บประวัติเหตุการณ์

### 🏛️ โครงสร้าง Event-Driven

```
┌─────────────────┐  ┌─────────────────┐
│  Order Service  │  │Payment Service  │
│  (Producer)     │  │  (Producer)     │
└────────┬────────┘  └────────┬────────┘
         │                    │
         └────────┬───────────┘
                  ↓
    ┌─────────────────────────────┐
    │   Event Broker / Bus        │
    │ (RabbitMQ, Kafka, Redis)   │
    └─────────────────────────────┘
                  │
    ┌─────┬──────┴──────┬──────────┐
    ↓     ↓             ↓          ↓
┌────────┐ ┌──────────┐ ┌────────┐ ┌──────────┐
│Email   │ │SMS       │ │Analytics│ │Cache     │
│Service │ │Service   │ │Service  │ │Invalidate│
│Consumer│ │Consumer  │ │Consumer │ │Consumer  │
└────────┘ └──────────┘ └────────┘ └──────────┘
```

### 📋 Event Flow

```
1. Order Service (Producer)
   - Order created
   - Publish event: "order.created"

   Event Data:
   {
     orderId: 123,
     userId: 45,
     total: 250,
     timestamp: now
   }

2. Event Broker receives
   - Store event
   - Route to subscribers

3. Multiple Consumers react
   - Email Service: Send confirmation
   - SMS Service: Send SMS
   - Inventory Service: Decrease stock
   - Analytics Service: Record sale
   - Cache Service: Invalidate cache

4. All happen asynchronously
   - ไม่ block Order Service
   - ทำเร็วขึ้น
```

### 📊 Real Examples

```
Uber Flow:
1. Ride Requested
   Event: "ride.requested"

2. Multiple reactions:
   - Matching Service: Find drivers
   - Notification Service: Notify drivers
   - Analytics Service: Record request
   - ETA Service: Calculate ETA

Amazon Flow:
1. Order Created
   Events:
   - "order.created"
   - "inventory.reserved"
   - "payment.processed"
   - "shipment.created"

2. Reactions:
   - Warehouse gets notification
   - Customer gets email
   - Analytics records sale
   - Recommendation engine updates
```

### ✅ ข้อดี Event-Driven

```
1. Loose Coupling
   - Producer ไม่รู้ Consumer
   - ง่ายเพิ่ม consumer ใหม่

2. Real-time Processing
   - ทันที ตอบสนอง
   - User experience ดี

3. Scalability
   - Consumer สามารถ scale independent
   - เพิ่ม consumers ได้ง่าย

4. Event History
   - เก็บทุก events
   - สามารถ replay
   - Audit trail

5. Parallel Processing
   - Multiple consumers ทำงาน parallel
   - เร็วขึ้น
```

### ❌ ข้อเสีย Event-Driven

```
1. Complexity
   - Flow ยากจะเข้าใจ
   - Debugging ยาก

2. Eventual Consistency
   - Data อาจไม่ consistent ชั่วขณะ
   - ต้องยอมรับ

3. Event Ordering
   - ต้องแน่ใจ event มา correct order
   - Challenging

4. Testing
   - Async testing ยาก
   - Integration testing ซับซ้อน

5. Monitoring
   - ต้อง sophisticated monitoring
   - หลาย components
```

### 💻 Code Example

```javascript
// Producer: Order Service
orderService.createOrder(data);

// Publish event
eventBus.publish("order.created", {
  orderId: order.id,
  userId: order.userId,
  total: order.total,
});

// Consumer 1: Email Service
eventBus.on("order.created", async (event) => {
  await emailService.sendConfirmation(event.userId);
});

// Consumer 2: Inventory Service
eventBus.on("order.created", async (event) => {
  await inventoryService.reserveItems(event);
});

// Consumer 3: Analytics Service
eventBus.on("order.created", (event) => {
  analytics.recordSale(event.total);
});

// All consumers react without blocking producer
```

### 🎓 สรุป Event-Driven

```
✨ Key Points:
1. Components communicate via events
2. Loose coupling
3. Real-time processing
4. Multiple consumers per event
5. Asynchronous
6. Good for: Real-time systems, high-volume
7. Bad for: Simple logic, strict consistency
```

---

## 🎨 ไฟล์ที่ 4: MVC Architecture (wk06-mvc-arch.md)

### 📝 บรรยายไฟล์

**MVC (Model-View-Controller)** คือรูปแบบคลาสสิกสำหรับ web applications โดยแบ่ง 3 ส่วน

### 🎯 ความสำคัญ

1. **Simplicity** - ง่ายเข้าใจ ทำได้เร็ว
2. **Proven Pattern** - ใช้มานาน ยาวนานแล้ว
3. **Server-side Rendering** - แสดง HTML ที่ server
4. **Traditional Web Apps** - Perfect สำหรับ traditional web

### 🏛️ โครงสร้าง MVC

```
┌──────────────────────────────┐
│   V: VIEW (HTML Templates)   │
│  - User Interface            │
│  - ejs, pug, handlebars      │
│  - No business logic         │
└──────────────┬───────────────┘
               │ Shows
               │
┌──────────────┼───────────────┐
│   C: CONTROLLER              │
│  - Receive HTTP request      │
│  - Call model                │
│  - Select view               │
│  - Send response             │
└──────────────┼───────────────┘
               │ Uses
               │
┌──────────────┴───────────────┐
│   M: MODEL                   │
│  - Database operations       │
│  - Business logic            │
│  - Validations               │
│  - Data processing           │
└──────────────────────────────┘
```

### 📋 Request-Response Cycle

```
1. User clicks: "Edit Profile"
   ↓
2. Browser: GET /users/5/edit
   ↓
3. Express Router
   ↓
4. UserController.editForm(req, res)
   - Extract ID from params
   - Call User.findById(5)
   ↓
5. Model (User)
   - Query database
   - Return user object
   ↓
6. Controller continues
   - Pass user to view
   - res.render('users/edit', { user })
   ↓
7. View (edit.ejs)
   - Receive user object
   - Render HTML form
   - Pre-fill with user data
   ↓
8. Browser
   - Receives HTML
   - Renders form
   - User edits and submits
   ↓
9. Browser: POST /users/5
   - Form data in body
   ↓
10. UserController.update()
    - Extract form data
    - Call User.update()
    ↓
11. Model
    - Update database
    ↓
12. Controller
    - Redirect to: /users/5
    ↓
13. Browser
    - Follow redirect
    - Shows updated user
```

### ✅ ข้อดี MVC

```
1. Simplicity
   - ง่ายเข้าใจ
   - ทำได้เร็ว

2. Separation of Concerns
   - Model: ข้อมูล
   - View: แสดงผล
   - Controller: ตรรกะ

3. Reusability
   - Controller reusable
   - Model reusable
   - View swappable

4. Testing
   - Model ทดสอบแยก
   - Controller ทดสอบ with mocks

5. Familiar
   - เป็นที่รู้จัก
   - Ruby on Rails, Django, Laravel

6. Server-side Rendering
   - SEO friendly
   - Fast initial load
```

### ❌ ข้อเสีย MVC

```
1. Fat Models
   - Model ใหญ่เกิน
   - ยากจัดการ

2. Fat Controllers
   - Controller เต็มไป business logic
   - ยากอ่าน

3. View Logic
   - Template มี logic มากเกิน
   - Hard to test

4. Monolithic
   - ระบบ 1 deployment
   - ยาก scale

5. Limited Scaling
   - Scale ทั้งระบบ
   - ไม่ scale feature เดี่ยว

6. Not for SPAs
   - Single Page Apps ต่างความต้องการ
   - React, Vue ดีกว่า
```

### 🤔 ใช้เมื่อใด

```
✅ ใช้เมื่อ:
- Traditional web applications
- Server-side rendering needed
- Small-medium projects
- Quick prototyping
- SEO important
- Team familiar with MVC
- HTML-based UI

❌ ไม่ใช้เมื่อ:
- Single Page Apps (SPAs)
- Microservices
- Multiple client types
- Real-time applications
- Need independent scaling
```

### 💻 Code Example

```javascript
// Model (User.js)
class User {
  static async findById(id) {
    return db.query('SELECT * FROM users WHERE id = ?', [id]);
  }

  async save() {
    // Validation
    // Insert to database
  }
}

// Controller (UserController.js)
class UserController {
  async show(req, res) {
    const user = await User.findById(req.params.id);
    res.render('users/show', { user });
  }
}

// View (users/show.ejs)
<h1><%= user.name %></h1>
<p><%= user.email %></p>

// Route (routes.js)
router.get('/users/:id', UserController.show);
```

### 📊 Real-world Examples

```
1. Ruby on Rails
   - Classic MVC
   - Model: ActiveRecord
   - View: ERB templates
   - Controller: RESTful

2. Django
   - Python MVC
   - Model: Django ORM
   - View: Templates
   - Controller: Views

3. Laravel
   - PHP MVC
   - Model: Eloquent
   - View: Blade
   - Controller: RESTful
```

### 🎓 สรุป MVC

```
✨ Key Points:
1. 3 parts: Model, View, Controller
2. Server-side rendering
3. Simple & proven
4. Good for traditional web
5. Not for SPAs
6. Easy to understand
7. Rapid development
```

---

## 🏛️ ไฟล์ที่ 5: Clean Architecture (wk06-clean-arch.md)

### 📝 บรรยายไฟล์

**Clean Architecture** คือ enterprise-level architecture ที่ business logic เป็นจุดศูนย์กลาง และไม่ขึ้นกับ frameworks

### 🎯 ความสำคัญ

1. **Framework-Independent** - เปลี่ยน frameworks ได้ง่าย
2. **Testable** - ทดสอบ logic โดยไม่ต้อง frameworks
3. **Long-term** - Maintainable ในระยะยาว
4. **Enterprise** - สำหรับโปรเจคใหญ่

### 🏛️ 4 วงกลม (Concentric Circles)

```
┌──────────────────────────────────────┐
│ OUTER: Frameworks & Drivers          │
│  - Express, Rails, Django            │
│  - MySQL, PostgreSQL, MongoDB        │
│  - React, Vue (if needed)            │
└──────────────────────────────────────┘
         ↑ depends on
         │
┌──────────────────────────────────────┐
│ Interface Adapters                   │
│  - Controllers                       │
│  - Repositories                      │
│  - Presenters                        │
│  - Gateways                          │
└──────────────────────────────────────┘
         ↑ depends on
         │
┌──────────────────────────────────────┐
│ Application Business Rules (UseCases)│
│  - CreateUserUseCase                 │
│  - ProcessPaymentUseCase             │
│  - GenerateReportUseCase             │
└──────────────────────────────────────┘
         ↑ depends on
         │
┌──────────────────────────────────────┐
│ INNER: Entities & Domain Logic       │
│  - User, Order, Product              │
│  - Pure business rules               │
│  - 0 dependencies                    │
└──────────────────────────────────────┘

KEY RULE: All dependencies point INWARD
```

### 📋 4 Layers อธิบาย

#### Layer 1: Entities (Core Business Logic)

```javascript
class User {
  constructor(id, email, name) {
    this.id = id;
    this.email = email;
    this.name = name;
  }

  isValidEmail() {
    return this.email.includes('@');
  }
}

Characteristics:
- Pure business logic
- NO external dependencies
- Most stable layer
- Least likely to change
- Can be tested without frameworks
```

#### Layer 2: Use Cases (Application Business Rules)

```javascript
class CreateUserUseCase {
  constructor(userRepository, emailService) {
    this.userRepository = userRepository;
    this.emailService = emailService;
  }

  async execute(request) {
    const user = new User(null, request.email, request.name);
    user.validate();
    const saved = await this.userRepository.save(user);
    await this.emailService.sendWelcome(saved);
    return saved;
  }
}

Characteristics:
- Orchestrate entities
- Use interfaces (abstraction)
- Application-specific logic
- Testable with mocks
```

#### Layer 3: Interface Adapters

```javascript
// Controllers
class UserController {
  constructor(createUserUseCase) {
    this.createUserUseCase = createUserUseCase;
  }

  async create(req, res) {
    const user = await this.createUserUseCase.execute(req.body);
    res.json(user);
  }
}

// Repositories
class MySQLUserRepository extends UserRepository {
  async save(user) {
    const [result] = await db.query(
      'INSERT INTO users ...',
      [user.email, user.name]
    );
    return user;
  }
}

Characteristics:
- Convert to/from use cases
- Framework-specific
- Most likely to change
```

#### Layer 4: Frameworks & Drivers

```javascript
// Express setup
const app = express();
const db = mysql.createPool({...});

// DI
const userRepository = new MySQLUserRepository(db);
const emailService = new NodemailerEmailService();
const createUserUseCase = new CreateUserUseCase(
  userRepository,
  emailService
);

const userController = new UserController(createUserUseCase);

app.post('/users', (req, res) => userController.create(req, res));

Characteristics:
- Framework code
- External integrations
- Most changeable
```

### 📊 The Dependency Rule

```
Golden Rule: Source code dependencies must point INWARD

CORRECT:
┌─────────────────────────┐
│ Controller              │
│   depends on            │
│        ↓                │
│ UseCase                 │
│   depends on            │
│        ↓                │
│ Entity                  │
└─────────────────────────┘

WRONG:
┌─────────────────────────┐
│ Entity                  │
│   depends on ❌          │
│        ↓                │
│ UseCase                 │
└─────────────────────────┘

Entity should NEVER depend on UseCase!
```

### ✅ ข้อดี Clean Architecture

```
1. Framework-Agnostic
   - เปลี่ยน Express → Fastify ได้ง่าย
   - เปลี่ยน MySQL → PostgreSQL ได้ง่าย

2. Testable
   - Test business logic ไม่ต้อง frameworks
   - Mock repositories ได้ง่าย

3. Independent
   - Business logic independent
   - สามารถ reuse ที่อื่น

4. Maintainability
   - Clear structure
   - ง่ายหาจุดแก้

5. Scalability
   - Grow ได้ long-term
   - ยังคง maintainable

6. Domain-Focused
   - Business logic at center
   - Framework at periphery
```

### ❌ ข้อเสีย Clean Architecture

```
1. Complexity
   - Layers เยอะ
   - Abstractions เยอะ

2. Over-engineering
   - Overkill สำหรับ simple projects
   - Too much structure

3. Learning Curve
   - ต้อง understand concepts
   - Require experience

4. Boilerplate
   - Code เยอะ
   - Setup ซับซ้อน

5. Performance
   - Extra layers = slight overhead

6. Team Expertise
   - ต้อง experienced developers
   - Junior developers struggle
```

### 🤔 ใช้เมื่อใด

```
✅ ใช้เมื่อ:
- Long-term projects
- Team > 10 developers
- Complex business logic
- Need framework independence
- Extensive testing critical
- Multiple platforms
- Enterprise application

❌ ไม่ใช้เมื่อ:
- MVP/Prototypes
- Small team (<5)
- Simple CRUD
- Fast time-to-market
- Simple business logic
- Learning new tech
```

### 💻 Code Example

```javascript
// Entity (Pure, 0 dependencies)
class User {
  constructor(email, name) {
    this.email = email;
    this.name = name;
  }
  validate() {
    if (!this.email.includes('@')) throw new Error('Invalid email');
  }
}

// Use Case (Depends on abstractions)
class CreateUserUseCase {
  constructor(userRepository, emailService) {
    this.userRepository = userRepository;
    this.emailService = emailService;
  }
  async execute(request) {
    const user = new User(request.email, request.name);
    user.validate();
    const saved = await this.userRepository.save(user);
    await this.emailService.send(saved);
    return saved;
  }
}

// Repository Interface
class UserRepository {
  async save(user) { throw new Error('Not implemented'); }
}

// Repository Implementation
class MySQLUserRepository extends UserRepository {
  async save(user) {
    const [result] = await db.query(...);
    user.id = result.insertId;
    return user;
  }
}

// Controller
class UserController {
  constructor(createUserUseCase) {
    this.createUserUseCase = createUserUseCase;
  }
  async create(req, res) {
    const user = await this.createUserUseCase.execute(req.body);
    res.status(201).json(user);
  }
}
```

### 📊 Real-world Examples

```
1. Enterprise Applications
   - 100+ developers
   - Multiple teams
   - Complex domain
   - Long-term maintenance

2. Startups (evolved)
   - Started with Layered
   - Grew to Microservices + Clean
   - Entities/UseCases reused

3. Open-source Projects
   - Framework independent
   - Multiple implementations
   - Community contributions
```

### 🎓 สรุป Clean Architecture

```
✨ Key Points:
1. 4 concentric circles
2. Business logic at center
3. All dependencies point inward
4. Framework-independent
5. Testable without frameworks
6. Good for: Enterprise, long-term
7. Bad for: Small projects, simple logic
```

---

## 📊 Comparison ทั้ง 5 Architecture

```
┌──────────────────────┬──────────┬─────────┬──────────┬──────┬────────┐
│ Aspect               │ Layered  │ Micro   │ Event    │ MVC  │ Clean  │
├──────────────────────┼──────────┼─────────┼──────────┼──────┼────────┤
│ Complexity           │ Low      │ Very Hi │ High     │ Low  │ High   │
│ Scalability          │ Medium   │ Very Hi │ High     │ Med  │ High   │
│ Team Size            │ 3-10     │ 50-1000 │ 8-15     │ 3-5  │ 10+    │
│ Testability          │ Good     │ Moderate│ Moderate │ Fair │ Excel  │
│ Deployment           │ Monolith │ Indepen │ Async    │ Mono │ Indepen│
│ Framework-Indep      │ No       │ No      │ No       │ No   │ YES    │
│ Learning Curve       │ Easy     │ Hard    │ Moderate │ Easy │ Hard   │
│ Boilerplate          │ Low      │ High    │ Moderate │ Low  │ Very Hi│
│ Best For             │ SME      │ Large   │ Real-tim │ Web  │ Enterpr│
│ Real-time            │ No       │ Yes     │ YES      │ No   │ No     │
│ Independent Services │ No       │ YES     │ Yes      │ No   │ No     │
└──────────────────────┴──────────┴─────────┴──────────┴──────┴────────┘
```

---

## 🎓 บทสรุปทั้งหมด

### 1️⃣ **Layered Architecture**

- ✅ Simple & Easy
- ✅ Good for small-medium teams
- ❌ Not scalable beyond a point
- 🎯 Use: Traditional web apps, MVPs

### 2️⃣ **Microservices Architecture**

- ✅ Scalable, independent, flexible
- ✅ Good for large teams
- ❌ Complex, operational overhead
- 🎯 Use: Large systems, multiple teams

### 3️⃣ **Event-Driven Architecture**

- ✅ Real-time, loose coupling, scalable
- ✅ Good for async processing
- ❌ Complex, eventual consistency
- 🎯 Use: Real-time systems (Uber, Netflix)

### 4️⃣ **MVC Architecture**

- ✅ Simple, proven, familiar
- ✅ Good for traditional web apps
- ❌ Monolithic, limited scaling
- 🎯 Use: Server-side rendered web apps

### 5️⃣ **Clean Architecture**

- ✅ Framework-independent, testable, maintainable
- ✅ Good for long-term, complex projects
- ❌ Overkill for simple projects, more code
- 🎯 Use: Enterprise apps, long-term projects

---

## 🤔 ตัดสินใจเลือก Architecture

### ขั้นตอน

```
1. ถามคำถาม
   - ทีมเท่าไหร่? (Team size)
   - โครงการเท่าไหร่? (Project scope)
   - ต้องใช้ tech ต่างกันไหม? (Tech diversity)
   - ต้องใช้ real-time ไหม? (Real-time)
   - ต้องเก็บ long-term ไหม? (Long-term)

2. ตรวจสอบเงื่อนไข
   - Team < 10: Layered หรือ MVC
   - Team 10-20: Layered + Clean
   - Team 20-100: Microservices + Clean
   - Real-time needs: Event-Driven
   - Enterprise: Clean Architecture

3. เลือก
   - Weigh pros & cons
   - Consider team expertise
   - Consider project timeline
   - Consider scalability needs

4. Implement
   - Start with base structure
   - Follow best practices
   - Evolve as needed
```

---

## ✅ สรุป

ในคอร์สนี้ เราได้เรียนรู้ **5 รูปแบบสถาปัตยกรรม** ที่สำคัญในการพัฒนาซอฟต์แวร์:

1. **Layered** - ง่าย ทำได้เร็ว สำหรับโครงการเล็ก
2. **Microservices** - Scalable สำหรับทีมใหญ่
3. **Event-Driven** - Real-time สำหรับระบบขนาดใหญ่
4. **MVC** - Proven สำหรับ web apps
5. **Clean** - Maintainable สำหรับ enterprise

**Key Takeaway:** ไม่มี architecture ที่ดีที่สุด มีแต่ architecture ที่เหมาะสมกับ use case นั้นๆ

---

**สำหรับการศึกษาเพิ่มเติม:**

- อ่านไฟล์ 5 ไฟล์ที่สร้างไว้
- ดูตัวอย่าง code
- ทำ practice projects
- ลองใช้ในโปรเจคจริง
