v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,155 @@
|
||||
# 백엔드 개발 가이드
|
||||
|
||||
> 그누보드7 백엔드 개발을 위한 종합 가이드입니다.
|
||||
|
||||
---
|
||||
|
||||
## 핵심 원칙
|
||||
|
||||
```text
|
||||
필수: FormRequest + Custom Rule 사용 (Service에 검증 로직 금지)
|
||||
필수: FormRequest + Custom Rule 패턴 사용
|
||||
✅ 필수: __() 함수를 사용한 다국어 처리
|
||||
✅ 필수: 상태/타입/분류는 Enum으로 정의
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<!-- AUTO-GENERATED-START: backend-readme-docs -->
|
||||
## 문서 목록
|
||||
|
||||
| 문서 | 제목 | 핵심 내용 |
|
||||
|------|------|----------|
|
||||
| [activity-log-hooks.md](activity-log-hooks.md) | 활동 로그 훅 레퍼런스 (Activity Log Hooks Reference) | 코어 66훅 + 이커머스 92훅 + 게시판 32훅 + 페이지 8훅 = 총 198훅 |
|
||||
| [activity-log.md](activity-log.md) | 활동 로그 시스템 (Activity Log System) | Monolog 기반: Service 훅 → Listener → Log::channel... |
|
||||
| [api-resources.md](api-resources.md) | API 리소스 | BaseApiResource 상속 필수 |
|
||||
| [authentication.md](authentication.md) | 인증 및 세션 처리 | Laravel Sanctum 토큰 전용 인증 (Bearer 토큰만 사용) |
|
||||
| [broadcasting.md](broadcasting.md) | Broadcasting (실시간 이벤트) | Laravel Reverb 사용 (WebSocket) |
|
||||
| [controllers.md](controllers.md) | 컨트롤러 계층 구조 | AdminBaseController / AuthBaseController / Publ... |
|
||||
| [core-config.md](core-config.md) | 코어 설정 (config/core.php) | config/core.php = 코어 권한/역할/메뉴/메일템플릿의 SSoT (Sing... |
|
||||
| [core-update-system.md](core-update-system.md) | 코어 업데이트 시스템 (Core Update System) | 코어 업그레이드 스텝: upgrades/ 디렉토리 (프로젝트 루트), 네임스페이스 A... |
|
||||
| [enum.md](enum.md) | Enum 사용 규칙 | 상태/타입/분류 = Enum 필수 (PHP 8.1+ Backed Enum) |
|
||||
| [exceptions.md](exceptions.md) | Custom Exception 다국어 처리 | 예외 메시지 하드코딩 금지 → __() 함수 필수 |
|
||||
| [middleware.md](middleware.md) | 미들웨어 등록 규칙 | 인증 필요 미들웨어 → 전역 등록 금지! |
|
||||
| [notification-system.md](notification-system.md) | 알림 시스템 (Notification System) | 모든 알림은 BaseNotification 상속 필수 (via() 보일러플레이트 제거) |
|
||||
| [response-helper.md](response-helper.md) | API 응답 규칙 (ResponseHelper) | 모든 API 응답은 ResponseHelper 사용 |
|
||||
| [routing.md](routing.md) | 라우트 네이밍 및 경로 | 모든 라우트는 name() 필수: ->name('api.users.index') |
|
||||
| [search-system.md](search-system.md) | Scout 검색 엔진 시스템 (Search System) | Laravel Scout + DatabaseFulltextEngine: MySQL F... |
|
||||
| [seo-system.md](seo-system.md) | SEO 페이지 생성기 시스템 (SEO Page Generator) | SeoMiddleware: 봇 요청 감지 → ?locale= 파라미터 해석 → Seo... |
|
||||
| [service-provider.md](service-provider.md) | 서비스 프로바이더 안전성 | DB 접근 전 .env 파일 존재 확인 필수 |
|
||||
| [service-repository.md](service-repository.md) | Service-Repository 패턴 | RepositoryInterface 주입 필수 (구체 클래스 직접 주입 금지) |
|
||||
| [validation.md](validation.md) | 검증 (Validation) | 필수: FormRequest에서 검증 (Service에 검증 로직 배치 금지) |
|
||||
|
||||
<!-- AUTO-GENERATED-END: backend-readme-docs -->
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 개요
|
||||
|
||||
### 계층 분리
|
||||
|
||||
```
|
||||
Controller → Request → Service → Repository → Model
|
||||
```
|
||||
|
||||
### 컨트롤러 계층 구조
|
||||
|
||||
```
|
||||
BaseApiController (최상위)
|
||||
├── AdminBaseController (관리자 전용)
|
||||
├── AuthBaseController (인증된 사용자)
|
||||
└── PublicBaseController (공개 API)
|
||||
```
|
||||
|
||||
### Service-Repository 패턴
|
||||
|
||||
```php
|
||||
// Service에서 훅 실행
|
||||
HookManager::doAction('module.entity.before_create', $data);
|
||||
$data = HookManager::applyFilters('module.entity.filter_data', $data);
|
||||
$result = $this->repository->create($data);
|
||||
HookManager::doAction('module.entity.after_create', $result);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 파사드 사용 규칙
|
||||
|
||||
```php
|
||||
// ✅ DO: 파사드 앞 역슬래시 제거
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
Log::info('메시지');
|
||||
Auth::user();
|
||||
|
||||
// ❌ DON'T: 역슬래시 사용
|
||||
\Log::info('메시지');
|
||||
auth()->user();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 핵심 규칙 요약
|
||||
|
||||
### 1. 검증 로직 위치
|
||||
|
||||
- ❌ Service 클래스에서 검증 금지
|
||||
- ✅ FormRequest에서 기본 검증
|
||||
- ✅ Custom Rule에서 복잡한 검증
|
||||
|
||||
### 2. 다국어 처리
|
||||
|
||||
- ❌ 하드코딩된 메시지 금지
|
||||
- ✅ `__()` 함수 사용 필수
|
||||
- ✅ `lang/ko/`, `lang/en/` 파일 관리
|
||||
|
||||
### 3. Enum 사용
|
||||
|
||||
- ❌ 문자열/숫자 상수 직접 사용 금지
|
||||
- ✅ Backed Enum 정의
|
||||
- ✅ 타입 힌트 활용
|
||||
|
||||
### 4. 미들웨어 등록
|
||||
|
||||
- ❌ 인증이 필요한 미들웨어를 글로벌 등록 금지
|
||||
- ✅ 그룹별 적절한 위치에 등록
|
||||
- ✅ 실행 순서 고려
|
||||
|
||||
### 5. 서비스 프로바이더 안전성
|
||||
|
||||
- ❌ .env 없이 실패하는 코드 금지
|
||||
- ✅ 환경 검증 후 로직 실행
|
||||
- ✅ 인스톨러 안정성 확보
|
||||
|
||||
---
|
||||
|
||||
## 빠른 참조
|
||||
|
||||
### 자주 사용하는 클래스
|
||||
|
||||
| 클래스 | 위치 | 용도 |
|
||||
|--------|------|------|
|
||||
| ResponseHelper | `app/Helpers/ResponseHelper.php` | API 응답 표준화 |
|
||||
| BaseApiResource | `app/Http/Resources/BaseApiResource.php` | API 리소스 기본 클래스 |
|
||||
| AdminBaseController | `app/Http/Controllers/Api/Admin/AdminBaseController.php` | 관리자 컨트롤러 |
|
||||
|
||||
### 훅 네이밍 규칙
|
||||
|
||||
```
|
||||
[vendor-module].[entity].[action]_[timing]
|
||||
|
||||
예시:
|
||||
sirsoft-ecommerce.product.before_create
|
||||
sirsoft-ecommerce.product.after_update
|
||||
sirsoft-ecommerce.product.filter_create_data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [AGENTS.md](../../../AGENTS.md) - 프로젝트 개발 가이드
|
||||
- [database-guide.md](../database-guide.md) - 데이터베이스 규칙
|
||||
- [extension/](../extension/) - 확장 시스템 (훅, 모듈, 플러그인)
|
||||
- [testing-guide.md](../testing-guide.md) - 테스트 규칙
|
||||
@@ -0,0 +1,714 @@
|
||||
# 활동 로그 훅 레퍼런스 (Activity Log Hooks Reference)
|
||||
|
||||
> 모든 ActivityLog 리스너가 구독하는 훅의 전체 목록 (코어 + 모듈)
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 코어 66훅 + 이커머스 92훅 + 게시판 32훅 + 페이지 8훅 = 총 198훅
|
||||
2. Listener에서 Log::channel('activity')->info() 직접 호출 (Monolog → ActivityLogHandler → DB)
|
||||
3. 스냅샷 패턴: before_update(priority 5) → 캡처, after_update → ChangeDetector로 비교
|
||||
4. 사용자 행위: ActivityLogType::User (장바구니/위시리스트/쿠폰 다운로드/주문/결제)
|
||||
5. 새 훅 추가 시: Listener에 구독 + lang 파일에 description_key 정의
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [아키텍처 개요](#1-아키텍처-개요)
|
||||
2. [코어 훅 (CoreActivityLogListener)](#2-코어-훅-coreactivityloglistener)
|
||||
3. [이커머스 모듈 훅](#3-이커머스-모듈-훅)
|
||||
4. [게시판 모듈 훅 (BoardActivityLogListener)](#4-게시판-모듈-훅-boardactivityloglistener)
|
||||
5. [페이지 모듈 훅 (PageActivityLogListener)](#5-페이지-모듈-훅-pageactivityloglistener)
|
||||
6. [스냅샷/변경감지 패턴](#6-스냅샷변경감지-패턴)
|
||||
7. [새 모듈에 ActivityLog 추가하기](#7-새-모듈에-activitylog-추가하기)
|
||||
|
||||
---
|
||||
|
||||
## 1. 아키텍처 개요
|
||||
|
||||
```text
|
||||
Service → doAction('hook.name') → ActivityLogListener → Log::channel('activity') → ActivityLogHandler → DB
|
||||
```
|
||||
|
||||
- **Listener**: `HookListenerInterface` 구현, `getSubscribedHooks()`로 훅-메서드 매핑 정의
|
||||
- **로그 기록**: `Log::channel('activity')->info($action, $context)` 직접 호출
|
||||
- **context 구조**: `log_type`, `loggable`, `description_key`, `description_params`, `properties`, `changes`
|
||||
- **LogType**: `ActivityLogType::Admin` (관리자 행위) / `ActivityLogType::User` (사용자 행위)
|
||||
- **변경 감지**: `ChangeDetector::detect($model, $snapshot)` — 스냅샷과 현재 상태 비교
|
||||
|
||||
---
|
||||
|
||||
## 2. 코어 훅 (CoreActivityLogListener)
|
||||
|
||||
**파일**: `app/Listeners/CoreActivityLogListener.php`
|
||||
**총 66훅** (스냅샷 캡처용 before 훅 포함)
|
||||
|
||||
### User (9훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.user.before_update` | `captureUserSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `core.user.after_create` | `handleUserAfterCreate` | `user.create` | Admin | User |
|
||||
| `core.user.after_update` | `handleUserAfterUpdate` | `user.update` | Admin | User |
|
||||
| `core.user.after_delete` | `handleUserAfterDelete` | `user.delete` | Admin | User |
|
||||
| `core.user.after_withdraw` | `handleUserAfterWithdraw` | `user.withdraw` | Admin | User |
|
||||
| `core.user.after_show` | `handleUserAfterShow` | `user.show` | Admin | User |
|
||||
| `core.user.after_list` | `handleUserAfterList` | `user.list` | Admin | - |
|
||||
| `core.user.after_search` | `handleUserAfterSearch` | `user.search` | Admin | - |
|
||||
| `sirsoft-core.user.after_bulk_update` | `handleUserAfterBulkUpdate` | `user.bulk_update` | Admin | - |
|
||||
|
||||
### Auth (6훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.auth.after_login` | `handleAuthAfterLogin` | `auth.login` | User | User |
|
||||
| `core.auth.logout` | `handleAuthLogout` | `auth.logout` | User | User |
|
||||
| `core.auth.register` | `handleAuthRegister` | `auth.register` | User | User |
|
||||
| `core.auth.forgot_password` | `handleAuthForgotPassword` | `auth.forgot_password` | User | - |
|
||||
| `core.auth.reset_password` | `handleAuthResetPassword` | `auth.reset_password` | User | - |
|
||||
| `core.auth.record_consents` | `handleAuthRecordConsents` | `auth.record_consents` | User | User |
|
||||
|
||||
### Role (6훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.role.before_update` | `captureRoleSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `core.role.after_create` | `handleRoleAfterCreate` | `role.create` | Admin | Role |
|
||||
| `core.role.after_update` | `handleRoleAfterUpdate` | `role.update` | Admin | Role |
|
||||
| `core.role.after_delete` | `handleRoleAfterDelete` | `role.delete` | Admin | Role |
|
||||
| `core.role.after_sync_permissions` | `handleRoleAfterSyncPermissions` | `role.sync_permissions` | Admin | Role |
|
||||
| `core.role.after_toggle_status` | `handleRoleAfterToggleStatus` | `role.toggle_status` | Admin | Role |
|
||||
|
||||
### Menu (7훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.menu.before_update` | `captureMenuSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `core.menu.after_create` | `handleMenuAfterCreate` | `menu.create` | Admin | Menu |
|
||||
| `core.menu.after_update` | `handleMenuAfterUpdate` | `menu.update` | Admin | Menu |
|
||||
| `core.menu.after_delete` | `handleMenuAfterDelete` | `menu.delete` | Admin | Menu |
|
||||
| `core.menu.after_update_order` | `handleMenuAfterUpdateOrder` | `menu.update_order` | Admin | - |
|
||||
| `core.menu.after_toggle_status` | `handleMenuAfterToggleStatus` | `menu.toggle_status` | Admin | Menu |
|
||||
| `core.menu.after_sync_roles` | `handleMenuAfterSyncRoles` | `menu.sync_roles` | Admin | Menu |
|
||||
|
||||
### Settings (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.settings.after_save` | `handleSettingsAfterSave` | `settings.save` | Admin | - |
|
||||
| `core.settings.after_set` | `handleSettingsAfterSet` | `settings.set` | Admin | - |
|
||||
|
||||
### Schedule (7훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.schedule.before_update` | `captureScheduleSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `core.schedule.after_create` | `handleScheduleAfterCreate` | `schedule.create` | Admin | Schedule |
|
||||
| `core.schedule.after_update` | `handleScheduleAfterUpdate` | `schedule.update` | Admin | Schedule |
|
||||
| `core.schedule.after_delete` | `handleScheduleAfterDelete` | `schedule.delete` | Admin | Schedule |
|
||||
| `core.schedule.after_run` | `handleScheduleAfterRun` | `schedule.run` | Admin | Schedule |
|
||||
| `core.schedule.after_bulk_update` | `handleScheduleAfterBulkUpdate` | `schedule.bulk_update` | Admin | - |
|
||||
| `core.schedule.after_bulk_delete` | `handleScheduleAfterBulkDelete` | `schedule.bulk_delete` | Admin | - |
|
||||
|
||||
### Attachment (3훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.attachment.after_upload` | `handleAttachmentAfterUpload` | `attachment.upload` | Admin | Attachment |
|
||||
| `core.attachment.after_delete` | `handleAttachmentAfterDelete` | `attachment.delete` | Admin | Attachment |
|
||||
| `core.attachment.after_bulk_delete` | `handleAttachmentAfterBulkDelete` | `attachment.bulk_delete` | Admin | - |
|
||||
|
||||
### Mail Template (3훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.mail_template.before_update` | `captureMailTemplateSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `core.mail_template.after_update` | `handleMailTemplateAfterUpdate` | `mail_template.update` | Admin | MailTemplate |
|
||||
| `core.mail_template.after_toggle_active` | `handleMailTemplateAfterToggleActive` | `mail_template.toggle_active` | Admin | MailTemplate |
|
||||
|
||||
### Module (6훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.modules.after_install` | `handleModuleAfterInstall` | `module.install` | Admin | - |
|
||||
| `core.modules.after_activate` | `handleModuleAfterActivate` | `module.activate` | Admin | - |
|
||||
| `core.modules.after_deactivate` | `handleModuleAfterDeactivate` | `module.deactivate` | Admin | - |
|
||||
| `core.modules.after_uninstall` | `handleModuleAfterUninstall` | `module.uninstall` | Admin | - |
|
||||
| `core.modules.after_update` | `handleModuleAfterUpdate` | `module.update` | Admin | - |
|
||||
| `core.modules.after_refresh_layouts` | `handleModuleAfterRefreshLayouts` | `module.refresh_layouts` | Admin | - |
|
||||
|
||||
### Plugin (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.plugins.after_install` | `handlePluginAfterInstall` | `plugin.install` | Admin | - |
|
||||
| `core.plugins.after_activate` | `handlePluginAfterActivate` | `plugin.activate` | Admin | - |
|
||||
| `core.plugins.after_deactivate` | `handlePluginAfterDeactivate` | `plugin.deactivate` | Admin | - |
|
||||
| `core.plugins.after_uninstall` | `handlePluginAfterUninstall` | `plugin.uninstall` | Admin | - |
|
||||
| `core.plugins.after_update` | `handlePluginAfterUpdate` | `plugin.update` | Admin | - |
|
||||
|
||||
### Template (6훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.templates.after_install` | `handleTemplateAfterInstall` | `template.install` | Admin | - |
|
||||
| `core.templates.after_activate` | `handleTemplateAfterActivate` | `template.activate` | Admin | - |
|
||||
| `core.templates.after_deactivate` | `handleTemplateAfterDeactivate` | `template.deactivate` | Admin | - |
|
||||
| `core.templates.after_uninstall` | `handleTemplateAfterUninstall` | `template.uninstall` | Admin | - |
|
||||
| `core.templates.after_version_update` | `handleTemplateAfterVersionUpdate` | `template.version_update` | Admin | - |
|
||||
| `core.templates.after_refresh_layouts` | `handleTemplateAfterRefreshLayouts` | `template.refresh_layouts` | Admin | - |
|
||||
|
||||
### Layout (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.layout.after_update` | `handleLayoutAfterUpdate` | `layout.update` | Admin | - |
|
||||
| `core.layout.after_version_restore` | `handleLayoutAfterVersionRestore` | `layout.version_restore` | Admin | - |
|
||||
|
||||
### Module Settings (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.module_settings.after_save` | `handleModuleSettingsAfterSave` | `module_settings.save` | Admin | - |
|
||||
| `core.module_settings.after_reset` | `handleModuleSettingsAfterReset` | `module_settings.reset` | Admin | - |
|
||||
|
||||
### Plugin Settings (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `core.plugin_settings.after_save` | `handlePluginSettingsAfterSave` | `plugin_settings.save` | Admin | - |
|
||||
| `core.plugin_settings.after_reset` | `handlePluginSettingsAfterReset` | `plugin_settings.reset` | Admin | - |
|
||||
|
||||
---
|
||||
|
||||
## 3. 이커머스 모듈 훅
|
||||
|
||||
**모듈**: `sirsoft-ecommerce`
|
||||
**총 92훅** (7개 Listener)
|
||||
|
||||
### 3.1 OrderActivityLogListener (21훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/OrderActivityLogListener.php`
|
||||
|
||||
#### OrderService (8훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.order.before_update` | `captureOrderSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.order.after_update` | `handleOrderAfterUpdate` | `order.update` | Admin | Order |
|
||||
| `sirsoft-ecommerce.order.after_delete` | `handleOrderAfterDelete` | `order.delete` | Admin | Order |
|
||||
| `sirsoft-ecommerce.order.after_bulk_update` | `handleOrderAfterBulkUpdate` | `order.bulk_update` | Admin | - |
|
||||
| `sirsoft-ecommerce.order.after_bulk_status_update` | `handleOrderAfterBulkStatusUpdate` | `order.bulk_status_update` | Admin | - |
|
||||
| `sirsoft-ecommerce.order.after_bulk_shipping_update` | `handleOrderAfterBulkShippingUpdate` | `order.bulk_shipping_update` | Admin | - |
|
||||
| `sirsoft-ecommerce.order.after_update_shipping_address` | `handleOrderAfterUpdateShippingAddress` | `order.update_shipping_address` | Admin | Order |
|
||||
| `sirsoft-ecommerce.order.after_send_email` | `handleOrderAfterSendEmail` | `order.send_email` | Admin | - |
|
||||
|
||||
#### OrderOptionService (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.order_option.after_status_change` | `handleOrderOptionAfterStatusChange` | `order_option.status_change` | Admin | OrderOption |
|
||||
| `sirsoft-ecommerce.order_option.after_bulk_status_change` | `handleOrderOptionAfterBulkStatusChange` | `order_option.bulk_status_change` | Admin | - |
|
||||
|
||||
#### OrderCancellationService (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.order.before_cancel` | `captureOrderCancelSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.order.after_cancel` | `handleOrderAfterCancel` | `order.cancel` | Admin | Order |
|
||||
| `sirsoft-ecommerce.order.after_partial_cancel` | `handleOrderAfterPartialCancel` | `order.partial_cancel` | Admin | Order |
|
||||
| `sirsoft-ecommerce.coupon.restore` | `handleCouponRestore` | `coupon.restore` | Admin | Order |
|
||||
| `sirsoft-ecommerce.mileage.restore` | `handleMileageRestore` | `mileage.restore` | Admin | Order |
|
||||
|
||||
#### OrderProcessingService (6훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.order.after_create` | `handleOrderAfterCreate` | `order.create` | **User** | Order |
|
||||
| `sirsoft-ecommerce.order.after_payment_complete` | `handleOrderAfterPaymentComplete` | `order.payment_complete` | **User** | Order |
|
||||
| `sirsoft-ecommerce.order.payment_failed` | `handleOrderAfterPaymentFailed` | `order.payment_failed` | **User** | Order |
|
||||
| `sirsoft-ecommerce.coupon.use` | `handleCouponUse` | `coupon.use` | **User** | Order |
|
||||
| `sirsoft-ecommerce.mileage.use` | `handleMileageUse` | `mileage.use` | **User** | Order |
|
||||
| `sirsoft-ecommerce.mileage.earn` | `handleMileageEarn` | `mileage.earn` | **User** | Order |
|
||||
|
||||
### 3.2 ProductActivityLogListener (10훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/ProductActivityLogListener.php`
|
||||
|
||||
> 이 리스너는 `ProductLogService`를 사용하는 별도 패턴입니다 (Log::channel 대신).
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Priority | 비고 |
|
||||
|---------|----------------|----------|------|
|
||||
| `sirsoft-ecommerce.product.after_create` | `logCreated` | 50 | 상품 생성 로그 |
|
||||
| `sirsoft-ecommerce.product.before_update` | `captureSnapshot` | 5 | 스냅샷 캡처 |
|
||||
| `sirsoft-ecommerce.product.after_update` | `logUpdated` | 50 | 변경사항 비교 후 로그 |
|
||||
| `sirsoft-ecommerce.product.before_delete` | `logDeleted` | 50 | 삭제 전 로그 기록 |
|
||||
| `sirsoft-ecommerce.product.before_bulk_update` | `captureProductBulkUpdateSnapshot` | 5 | 일괄 수정 전 스냅샷 |
|
||||
| `sirsoft-ecommerce.product.after_bulk_update` | `handleProductAfterBulkUpdate` | 20 | 일괄 수정 로그 |
|
||||
| `sirsoft-ecommerce.product.before_bulk_price_update` | `captureProductBulkPriceSnapshot` | 5 | 일괄 가격 수정 전 스냅샷 |
|
||||
| `sirsoft-ecommerce.product.after_bulk_price_update` | `handleProductAfterBulkPriceUpdate` | 20 | 일괄 가격 수정 로그 |
|
||||
| `sirsoft-ecommerce.product.before_bulk_stock_update` | `captureProductBulkStockSnapshot` | 5 | 일괄 재고 수정 전 스냅샷 |
|
||||
| `sirsoft-ecommerce.product.after_bulk_stock_update` | `handleProductAfterBulkStockUpdate` | 20 | 일괄 재고 수정 로그 |
|
||||
|
||||
### 3.3 CouponActivityLogListener (6훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/CouponActivityLogListener.php`
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.coupon.after_create` | `handleAfterCreate` | `coupon.create` | Admin | Coupon |
|
||||
| `sirsoft-ecommerce.coupon.before_update` | `captureCouponSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.coupon.after_update` | `handleAfterUpdate` | `coupon.update` | Admin | Coupon |
|
||||
| `sirsoft-ecommerce.coupon.after_delete` | `handleAfterDelete` | `coupon.delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.coupon.before_bulk_status` | `captureCouponBulkStatusSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.coupon.after_bulk_status` | `handleAfterBulkStatus` | `coupon.bulk_status` | Admin | - |
|
||||
|
||||
### 3.4 ShippingPolicyActivityLogListener (8훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/ShippingPolicyActivityLogListener.php`
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.shipping_policy.after_create` | `handleAfterCreate` | `shipping_policy.create` | Admin | ShippingPolicy |
|
||||
| `sirsoft-ecommerce.shipping_policy.before_update` | `captureSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_update` | `handleAfterUpdate` | `shipping_policy.update` | Admin | ShippingPolicy |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_delete` | `handleAfterDelete` | `shipping_policy.delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_toggle_active` | `handleAfterToggleActive` | `shipping_policy.toggle_active` | Admin | ShippingPolicy |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_set_default` | `handleAfterSetDefault` | `shipping_policy.set_default` | Admin | ShippingPolicy |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_bulk_delete` | `handleAfterBulkDelete` | `shipping_policy.bulk_delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_bulk_toggle_active` | `handleAfterBulkToggleActive` | `shipping_policy.bulk_toggle_active` | Admin | - |
|
||||
|
||||
### 3.5 CategoryActivityLogListener (6훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/CategoryActivityLogListener.php`
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.category.after_create` | `handleAfterCreate` | `category.create` | Admin | Category |
|
||||
| `sirsoft-ecommerce.category.before_update` | `captureCategorySnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.category.after_update` | `handleAfterUpdate` | `category.update` | Admin | Category |
|
||||
| `sirsoft-ecommerce.category.after_delete` | `handleAfterDelete` | `category.delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.category.after_toggle_status` | `handleAfterToggleStatus` | `category.toggle_status` | Admin | Category |
|
||||
| `sirsoft-ecommerce.category.after_reorder` | `handleAfterReorder` | `category.reorder` | Admin | - |
|
||||
|
||||
### 3.6 EcommerceAdminActivityLogListener (51훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/EcommerceAdminActivityLogListener.php`
|
||||
|
||||
#### Brand (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.brand.after_create` | `handleBrandAfterCreate` | `brand.create` | Admin | Brand |
|
||||
| `sirsoft-ecommerce.brand.before_update` | `captureBrandSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.brand.after_update` | `handleBrandAfterUpdate` | `brand.update` | Admin | Brand |
|
||||
| `sirsoft-ecommerce.brand.after_delete` | `handleBrandAfterDelete` | `brand.delete` | Admin | Brand |
|
||||
| `sirsoft-ecommerce.brand.after_toggle_status` | `handleBrandAfterToggleStatus` | `brand.toggle_status` | Admin | Brand |
|
||||
|
||||
#### ProductLabel (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.label.after_create` | `handleLabelAfterCreate` | `label.create` | Admin | ProductLabel |
|
||||
| `sirsoft-ecommerce.label.before_update` | `captureLabelSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.label.after_update` | `handleLabelAfterUpdate` | `label.update` | Admin | ProductLabel |
|
||||
| `sirsoft-ecommerce.label.after_delete` | `handleLabelAfterDelete` | `label.delete` | Admin | ProductLabel |
|
||||
| `sirsoft-ecommerce.label.after_toggle_status` | `handleLabelAfterToggleStatus` | `label.toggle_status` | Admin | ProductLabel |
|
||||
|
||||
#### ProductCommonInfo (4훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.product-common-info.after_create` | `handleCommonInfoAfterCreate` | `common_info.create` | Admin | ProductCommonInfo |
|
||||
| `sirsoft-ecommerce.product-common-info.before_update` | `captureCommonInfoSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.product-common-info.after_update` | `handleCommonInfoAfterUpdate` | `common_info.update` | Admin | ProductCommonInfo |
|
||||
| `sirsoft-ecommerce.product-common-info.after_delete` | `handleCommonInfoAfterDelete` | `common_info.delete` | Admin | ProductCommonInfo |
|
||||
|
||||
#### ProductNoticeTemplate (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.product-notice-template.after_create` | `handleNoticeTemplateAfterCreate` | `notice_template.create` | Admin | ProductNoticeTemplate |
|
||||
| `sirsoft-ecommerce.product-notice-template.before_update` | `captureNoticeTemplateSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.product-notice-template.after_update` | `handleNoticeTemplateAfterUpdate` | `notice_template.update` | Admin | ProductNoticeTemplate |
|
||||
| `sirsoft-ecommerce.product-notice-template.after_delete` | `handleNoticeTemplateAfterDelete` | `notice_template.delete` | Admin | ProductNoticeTemplate |
|
||||
| `sirsoft-ecommerce.product-notice-template.after_copy` | `handleNoticeTemplateAfterCopy` | `notice_template.copy` | Admin | ProductNoticeTemplate |
|
||||
|
||||
#### ExtraFeeTemplate (10훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_create` | `handleExtraFeeAfterCreate` | `extra_fee_template.create` | Admin | ExtraFeeTemplate |
|
||||
| `sirsoft-ecommerce.extra_fee_template.before_update` | `captureExtraFeeSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_update` | `handleExtraFeeAfterUpdate` | `extra_fee_template.update` | Admin | ExtraFeeTemplate |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_delete` | `handleExtraFeeAfterDelete` | `extra_fee_template.delete` | Admin | ExtraFeeTemplate |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_toggle_active` | `handleExtraFeeAfterToggleActive` | `extra_fee_template.toggle_active` | Admin | ExtraFeeTemplate |
|
||||
| `sirsoft-ecommerce.extra_fee_template.before_bulk_delete` | `captureExtraFeeBulkDeleteSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_bulk_delete` | `handleExtraFeeAfterBulkDelete` | `extra_fee_template.bulk_delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.extra_fee_template.before_bulk_toggle_active` | `captureExtraFeeBulkToggleSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_bulk_toggle_active` | `handleExtraFeeAfterBulkToggleActive` | `extra_fee_template.bulk_toggle_active` | Admin | - |
|
||||
| `sirsoft-ecommerce.extra_fee_template.after_bulk_create` | `handleExtraFeeAfterBulkCreate` | `extra_fee_template.bulk_create` | Admin | - |
|
||||
|
||||
#### ShippingCarrier (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.shipping_carrier.after_create` | `handleCarrierAfterCreate` | `shipping_carrier.create` | Admin | ShippingCarrier |
|
||||
| `sirsoft-ecommerce.shipping_carrier.before_update` | `captureCarrierSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.shipping_carrier.after_update` | `handleCarrierAfterUpdate` | `shipping_carrier.update` | Admin | ShippingCarrier |
|
||||
| `sirsoft-ecommerce.shipping_carrier.after_delete` | `handleCarrierAfterDelete` | `shipping_carrier.delete` | Admin | ShippingCarrier |
|
||||
| `sirsoft-ecommerce.shipping_carrier.after_toggle_status` | `handleCarrierAfterToggleStatus` | `shipping_carrier.toggle_status` | Admin | ShippingCarrier |
|
||||
|
||||
#### ProductImage (3훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.product-image.after_upload` | `handleImageAfterUpload` | `product_image.upload` | Admin | ProductImage |
|
||||
| `sirsoft-ecommerce.product-image.after_delete` | `handleImageAfterDelete` | `product_image.delete` | Admin | ProductImage |
|
||||
| `sirsoft-ecommerce.product-image.after_reorder` | `handleImageAfterReorder` | `product_image.reorder` | Admin | - |
|
||||
|
||||
#### ShippingPolicy Bulk (4훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.shipping_policy.before_bulk_delete` | `captureShippingPolicyBulkDeleteSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_bulk_delete` | `handleShippingPolicyAfterBulkDelete` | `shipping_policy.bulk_delete` | Admin | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.before_bulk_toggle_active` | `captureShippingPolicyBulkToggleSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.shipping_policy.after_bulk_toggle_active` | `handleShippingPolicyAfterBulkToggleActive` | `shipping_policy.bulk_toggle_active` | Admin | - |
|
||||
|
||||
#### ProductOption (6훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.product_option.before_bulk_price_update` | `captureOptionBulkPriceSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.product_option.after_bulk_price_update` | `handleOptionAfterBulkPriceUpdate` | `product_option.bulk_price_update` | Admin | - |
|
||||
| `sirsoft-ecommerce.product_option.before_bulk_stock_update` | `captureOptionBulkStockSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.product_option.after_bulk_stock_update` | `handleOptionAfterBulkStockUpdate` | `product_option.bulk_stock_update` | Admin | - |
|
||||
| `sirsoft-ecommerce.option.before_bulk_update` | `captureOptionBulkUpdateSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.option.after_bulk_update` | `handleOptionAfterBulkUpdate` | `product_option.bulk_update` | Admin | - |
|
||||
|
||||
#### ProductReview (4훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.product-review.after_create` | `handleReviewAfterCreate` | `review.create` | Admin | ProductReview |
|
||||
| `sirsoft-ecommerce.product-review.after_delete` | `handleReviewAfterDelete` | `review.delete` | Admin | ProductReview |
|
||||
| `sirsoft-ecommerce.product-review.before_bulk_delete` | `captureReviewBulkDeleteSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-ecommerce.product-review.after_bulk_delete` | `handleReviewAfterBulkDelete` | `product_review.bulk_delete` | Admin | - |
|
||||
|
||||
### 3.7 EcommerceUserActivityLogListener (7훅)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-ecommerce/src/Listeners/EcommerceUserActivityLogListener.php`
|
||||
|
||||
#### Cart (5훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.cart.after_add` | `handleCartAfterAdd` | `cart.add` | **User** | Cart |
|
||||
| `sirsoft-ecommerce.cart.after_update_quantity` | `handleCartAfterUpdateQuantity` | `cart.update_quantity` | **User** | Cart |
|
||||
| `sirsoft-ecommerce.cart.after_change_option` | `handleCartAfterChangeOption` | `cart.change_option` | **User** | Cart |
|
||||
| `sirsoft-ecommerce.cart.after_delete` | `handleCartAfterDelete` | `cart.delete` | **User** | - |
|
||||
| `sirsoft-ecommerce.cart.after_delete_all` | `handleCartAfterDeleteAll` | `cart.delete_all` | **User** | - |
|
||||
|
||||
#### Wishlist (1훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.wishlist.after_toggle` | `handleWishlistAfterToggle` | `wishlist.add` / `wishlist.remove` | **User** | Product |
|
||||
|
||||
#### User Coupon (1훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-ecommerce.user_coupon.after_download` | `handleUserCouponAfterDownload` | `user_coupon.download` | **User** | CouponIssue |
|
||||
|
||||
---
|
||||
|
||||
## 4. 게시판 모듈 훅 (BoardActivityLogListener)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-board/src/Listeners/BoardActivityLogListener.php`
|
||||
**총 32훅**
|
||||
|
||||
### Board (6훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.board.after_create` | `handleBoardAfterCreate` | `board.create` | Admin | Board |
|
||||
| `sirsoft-board.board.before_update` | `captureBoardSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-board.board.after_update` | `handleBoardAfterUpdate` | `board.update` | Admin | Board |
|
||||
| `sirsoft-board.board.after_delete` | `handleBoardAfterDelete` | `board.delete` | Admin | Board |
|
||||
| `sirsoft-board.board.after_add_to_menu` | `handleBoardAfterAddToMenu` | `board.add_to_menu` | Admin | Board |
|
||||
| `sirsoft-board.settings.after_bulk_apply` | `handleSettingsAfterBulkApply` | `board_settings.bulk_apply` | Admin | - |
|
||||
|
||||
### BoardType (4훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.board_type.after_create` | `handleBoardTypeAfterCreate` | `board_type.create` | Admin | BoardType |
|
||||
| `sirsoft-board.board_type.before_update` | `captureBoardTypeSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-board.board_type.after_update` | `handleBoardTypeAfterUpdate` | `board_type.update` | Admin | BoardType |
|
||||
| `sirsoft-board.board_type.after_delete` | `handleBoardTypeAfterDelete` | `board_type.delete` | Admin | BoardType |
|
||||
|
||||
### Post (6훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.post.after_create` | `handlePostAfterCreate` | `post.create` | Admin | Post |
|
||||
| `sirsoft-board.post.before_update` | `capturePostSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-board.post.after_update` | `handlePostAfterUpdate` | `post.update` | Admin | Post |
|
||||
| `sirsoft-board.post.after_delete` | `handlePostAfterDelete` | `post.delete` | Admin | Post |
|
||||
| `sirsoft-board.post.after_blind` | `handlePostAfterBlind` | `post.blind` | Admin | Post |
|
||||
| `sirsoft-board.post.after_restore` | `handlePostAfterRestore` | `post.restore` | Admin | Post |
|
||||
|
||||
### Comment (6훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.comment.after_create` | `handleCommentAfterCreate` | `comment.create` | Admin | Comment |
|
||||
| `sirsoft-board.comment.before_update` | `captureCommentSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-board.comment.after_update` | `handleCommentAfterUpdate` | `comment.update` | Admin | Comment |
|
||||
| `sirsoft-board.comment.after_delete` | `handleCommentAfterDelete` | `comment.delete` | Admin | Comment |
|
||||
| `sirsoft-board.comment.after_blind` | `handleCommentAfterBlind` | `comment.blind` | Admin | Comment |
|
||||
| `sirsoft-board.comment.after_restore` | `handleCommentAfterRestore` | `comment.restore` | Admin | Comment |
|
||||
|
||||
### Attachment (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.attachment.after_upload` | `handleAttachmentAfterUpload` | `attachment.upload` | Admin | Attachment |
|
||||
| `sirsoft-board.attachment.after_delete` | `handleAttachmentAfterDelete` | `attachment.delete` | Admin | Attachment |
|
||||
|
||||
### Report (8훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-board.report.after_create` | `handleReportAfterCreate` | `report.create` | Admin | Report |
|
||||
| `sirsoft-board.report.after_update_status` | `handleReportAfterUpdateStatus` | `report.update_status` | Admin | Report |
|
||||
| `sirsoft-board.report.before_bulk_update_status` | `captureReportBulkStatusSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-board.report.after_bulk_update_status` | `handleReportAfterBulkUpdateStatus` | `report.bulk_update_status` | Admin | - |
|
||||
| `sirsoft-board.report.after_delete` | `handleReportAfterDelete` | `report.delete` | Admin | Report |
|
||||
| `sirsoft-board.report.after_restore_content` | `handleReportAfterRestoreContent` | `report.restore_content` | Admin | Report |
|
||||
| `sirsoft-board.report.after_blind_content` | `handleReportAfterBlindContent` | `report.blind_content` | Admin | Report |
|
||||
| `sirsoft-board.report.after_delete_content` | `handleReportAfterDeleteContent` | `report.delete_content` | Admin | Report |
|
||||
|
||||
---
|
||||
|
||||
## 5. 페이지 모듈 훅 (PageActivityLogListener)
|
||||
|
||||
**파일**: `modules/_bundled/sirsoft-page/src/Listeners/PageActivityLogListener.php`
|
||||
**총 8훅**
|
||||
|
||||
### Page (6훅, 스냅샷 포함)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-page.page.after_create` | `handlePageAfterCreate` | `page.create` | Admin | Page |
|
||||
| `sirsoft-page.page.before_update` | `capturePageSnapshot` | _(스냅샷 캡처)_ | - | - |
|
||||
| `sirsoft-page.page.after_update` | `handlePageAfterUpdate` | `page.update` | Admin | Page |
|
||||
| `sirsoft-page.page.after_delete` | `handlePageAfterDelete` | `page.delete` | Admin | Page |
|
||||
| `sirsoft-page.page.after_publish` | `handlePageAfterPublish` | `page.publish` / `page.unpublish` | Admin | Page |
|
||||
| `sirsoft-page.page.after_restore` | `handlePageAfterRestore` | `page.restore` | Admin | Page |
|
||||
|
||||
### PageAttachment (2훅)
|
||||
|
||||
| 훅 이름 | Listener 메서드 | Action (DB) | LogType | Loggable |
|
||||
|---------|----------------|-------------|---------|----------|
|
||||
| `sirsoft-page.attachment.after_upload` | `handleAttachmentAfterUpload` | `page_attachment.upload` | Admin | PageAttachment |
|
||||
| `sirsoft-page.attachment.after_delete` | `handleAttachmentAfterDelete` | `page_attachment.delete` | Admin | PageAttachment |
|
||||
|
||||
---
|
||||
|
||||
## 6. 스냅샷/변경감지 패턴
|
||||
|
||||
ActivityLog에서 수정(update) 작업의 변경 이력을 기록하려면 **스냅샷 패턴**을 사용합니다.
|
||||
|
||||
### 동작 흐름
|
||||
|
||||
```text
|
||||
1. Service에서 before_update 훅 발행 (doAction)
|
||||
2. Listener의 캡처 메서드 실행 (priority: 5, 다른 리스너보다 먼저)
|
||||
→ 현재 모델 상태를 $snapshots 배열에 저장
|
||||
3. Service에서 실제 DB 업데이트 수행
|
||||
4. Service에서 after_update 훅 발행 (doAction)
|
||||
5. Listener의 핸들러 메서드 실행 (priority: 20)
|
||||
→ ChangeDetector::detect($model, $snapshot) 호출
|
||||
→ 변경된 필드만 추출하여 로그 기록
|
||||
→ 스냅샷 정리 (unset)
|
||||
```
|
||||
|
||||
### 코드 예시
|
||||
|
||||
```php
|
||||
// 1. getSubscribedHooks()에서 before/after 쌍 등록
|
||||
public static function getSubscribedHooks(): array
|
||||
{
|
||||
return [
|
||||
'my-module.entity.before_update' => ['method' => 'captureSnapshot', 'priority' => 5],
|
||||
'my-module.entity.after_update' => ['method' => 'handleAfterUpdate', 'priority' => 20],
|
||||
];
|
||||
}
|
||||
|
||||
// 2. 스냅샷 캡처 (before_update, priority 5)
|
||||
public function captureSnapshot(Model $entity, array $data): void
|
||||
{
|
||||
$this->snapshots['entity_' . $entity->id] = $entity->toArray();
|
||||
}
|
||||
|
||||
// 3. 변경 감지 + 로그 기록 (after_update, priority 20)
|
||||
public function handleAfterUpdate(Model $entity): void
|
||||
{
|
||||
$snapshot = $this->snapshots['entity_' . $entity->id] ?? null;
|
||||
$changes = ChangeDetector::detect($entity, $snapshot);
|
||||
|
||||
Log::channel('activity')->info('entity.update', [
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'loggable' => $entity,
|
||||
'description_key' => 'my-module::activity_log.description.entity_update',
|
||||
'description_params' => ['entity_id' => $entity->id],
|
||||
'changes' => $changes,
|
||||
]);
|
||||
|
||||
unset($this->snapshots['entity_' . $entity->id]);
|
||||
}
|
||||
```
|
||||
|
||||
### ChangeDetector
|
||||
|
||||
**파일**: `app/ActivityLog/ChangeDetector.php`
|
||||
|
||||
- 모델의 `$activityLogFields` 속성에 정의된 필드만 비교
|
||||
- 각 필드의 `label_key` (다국어 키)를 포함한 구조화된 변경 이력 생성
|
||||
- `BackedEnum` 자동 변환 지원
|
||||
- 스냅샷이 `null`이면 `null` 반환 (변경 없음)
|
||||
|
||||
### ProductActivityLogListener의 별도 패턴
|
||||
|
||||
`ProductActivityLogListener`는 `ProductLogService`를 주입받아 사용하는 별도 패턴입니다:
|
||||
- `ChangeDetector` 대신 자체 `detectChanges()` 메서드로 변경 감지
|
||||
- 해시 비교로 옵션/추가옵션/이미지 변경 감지
|
||||
- `Log::channel('activity')` 대신 `ProductLogService`를 통해 처리로그 테이블에 기록
|
||||
|
||||
---
|
||||
|
||||
## 7. 새 모듈에 ActivityLog 추가하기
|
||||
|
||||
### Step 1: Listener 클래스 생성
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Vendor\MyModule\Listeners;
|
||||
|
||||
use App\ActivityLog\ChangeDetector;
|
||||
use App\Contracts\Extension\HookListenerInterface;
|
||||
use App\Enums\ActivityLogType;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class MyModuleActivityLogListener implements HookListenerInterface
|
||||
{
|
||||
private array $snapshots = [];
|
||||
|
||||
public static function getSubscribedHooks(): array
|
||||
{
|
||||
return [
|
||||
'vendor-mymodule.entity.after_create' => ['method' => 'handleAfterCreate', 'priority' => 20],
|
||||
'vendor-mymodule.entity.before_update' => ['method' => 'captureSnapshot', 'priority' => 5],
|
||||
'vendor-mymodule.entity.after_update' => ['method' => 'handleAfterUpdate', 'priority' => 20],
|
||||
'vendor-mymodule.entity.after_delete' => ['method' => 'handleAfterDelete', 'priority' => 20],
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(...$args): void
|
||||
{
|
||||
// 개별 메서드에서 처리
|
||||
}
|
||||
|
||||
// ... 각 핸들러 메서드 구현
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: module.php에 Listener 등록
|
||||
|
||||
```php
|
||||
// module.php의 listeners 배열에 추가
|
||||
'listeners' => [
|
||||
MyModuleActivityLogListener::class,
|
||||
],
|
||||
```
|
||||
|
||||
### Step 3: 다국어 파일에 description_key 정의
|
||||
|
||||
```php
|
||||
// lang/ko/activity_log.php
|
||||
return [
|
||||
'description' => [
|
||||
'entity_create' => ':entity_name 엔티티가 생성되었습니다.',
|
||||
'entity_update' => ':entity_name 엔티티가 수정되었습니다.',
|
||||
'entity_delete' => ':entity_name 엔티티가 삭제되었습니다.',
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
### Step 4: 모델에 $activityLogFields 정의 (ChangeDetector 사용 시)
|
||||
|
||||
```php
|
||||
// Model 클래스에 추가
|
||||
protected array $activityLogFields = [
|
||||
'name' => ['label_key' => 'vendor-mymodule::activity_log.fields.name'],
|
||||
'status' => ['label_key' => 'vendor-mymodule::activity_log.fields.status'],
|
||||
];
|
||||
```
|
||||
|
||||
### Step 5: 테스트 작성
|
||||
|
||||
```php
|
||||
// tests/Unit/Listeners/MyModuleActivityLogListenerTest.php
|
||||
class MyModuleActivityLogListenerTest extends TestCase
|
||||
{
|
||||
public function test_getSubscribedHooks_returns_expected_hooks(): void
|
||||
{
|
||||
$hooks = MyModuleActivityLogListener::getSubscribedHooks();
|
||||
|
||||
$this->assertArrayHasKey('vendor-mymodule.entity.after_create', $hooks);
|
||||
$this->assertArrayHasKey('vendor-mymodule.entity.before_update', $hooks);
|
||||
// ...
|
||||
}
|
||||
|
||||
public function test_handleAfterCreate_logs_activity(): void
|
||||
{
|
||||
Log::shouldReceive('channel')
|
||||
->with('activity')
|
||||
->andReturnSelf();
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('entity.create', Mockery::type('array'));
|
||||
|
||||
$listener = new MyModuleActivityLogListener();
|
||||
$listener->handleAfterCreate($entity, $data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 훅 네이밍 규칙
|
||||
|
||||
| 패턴 | 용도 | Priority |
|
||||
|------|------|----------|
|
||||
| `{module}.{entity}.before_update` | 스냅샷 캡처 | 5 (높은 우선순위) |
|
||||
| `{module}.{entity}.after_create` | 생성 로그 | 20 |
|
||||
| `{module}.{entity}.after_update` | 수정 로그 (변경감지) | 20 |
|
||||
| `{module}.{entity}.after_delete` | 삭제 로그 | 20 |
|
||||
| `{module}.{entity}.after_bulk_*` | 일괄 작업 로그 | 20 |
|
||||
| `{module}.{entity}.after_toggle_*` | 상태 전환 로그 | 20 |
|
||||
|
||||
### context 구조
|
||||
|
||||
| 키 | 타입 | 설명 | 필수 |
|
||||
|----|------|------|------|
|
||||
| `log_type` | `ActivityLogType` | Admin 또는 User | O |
|
||||
| `loggable` | `Model` | 대상 모델 (polymorphic) | - |
|
||||
| `description_key` | `string` | 다국어 설명 키 | O |
|
||||
| `description_params` | `array` | 설명 파라미터 | - |
|
||||
| `properties` | `array` | 추가 속성 (JSON) | - |
|
||||
| `changes` | `array\|null` | ChangeDetector 결과 | - |
|
||||
@@ -0,0 +1,955 @@
|
||||
# 활동 로그 시스템 (Activity Log System)
|
||||
|
||||
G7의 활동 로그는 Monolog 기반 커스텀 채널을 통해 DB에 기록됩니다.
|
||||
Service 훅 이벤트를 Listener가 수신하여 `Log::channel('activity')` 로 전달하고,
|
||||
ActivityLogHandler가 `activity_logs` 테이블에 저장합니다.
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. Monolog 기반: Service 훅 → Listener → Log::channel('activity') → Handler → DB (3단계)
|
||||
2. ActivityLogService는 조회 전용 (기록 메서드 없음 — Log::channel 직접 사용)
|
||||
3. description_params에 ID 저장 → ActivityLogDescriptionResolver가 표시 시 이름 변환
|
||||
4. 변경 추적: $activityLogFields 정의 필수 + ChangeDetector → changes JSON (미정의 시 null)
|
||||
5. Bulk 작업 Per-Item 필수: N건 처리 시 N건 개별 로그 (집계 1건 금지), 삭제 시 loggable_type/loggable_id 직접 지정
|
||||
6. 새 모듈 추가 시: Listener + DescriptionResolver + module.php 등록 + lang + $activityLogFields
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [아키텍처](#아키텍처)
|
||||
2. [로깅 흐름](#로깅-흐름)
|
||||
3. [Listener 작성 패턴](#listener-작성-패턴)
|
||||
4. [변경 추적 (ChangeDetector)](#변경-추적-changedetector)
|
||||
5. [다국어 키 규칙](#다국어-키-규칙)
|
||||
6. [description_params 저장 정책](#description_params-저장-정책)
|
||||
7. [ActivityLogDescriptionResolver 규정](#activitylogdescriptionresolver-규정)
|
||||
8. [모듈 리스너 등록](#모듈-리스너-등록)
|
||||
9. [모델별 로그 조회 API 패턴](#모델별-로그-조회-api-패턴)
|
||||
10. [Bulk 로깅 패턴 (Per-Item 필수)](#bulk-로깅-패턴-per-item-필수)
|
||||
11. [DB 스키마](#db-스키마)
|
||||
12. [인덱스](#인덱스)
|
||||
13. [금지 사항](#금지-사항)
|
||||
14. [개발자 체크리스트](#개발자-체크리스트)
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처
|
||||
|
||||
### Monolog 기반 3단계 파이프라인
|
||||
|
||||
```text
|
||||
Service (doAction 훅 발행)
|
||||
↓
|
||||
Listener (CoreActivityLogListener / 모듈 XxxActivityLogListener)
|
||||
↓
|
||||
Log::channel('activity')->info($action, $context)
|
||||
↓
|
||||
ActivityLogProcessor (user_id, ip_address, user_agent 자동 주입)
|
||||
↓
|
||||
ActivityLogHandler (Monolog Handler → activity_logs 테이블 INSERT)
|
||||
```
|
||||
|
||||
### 핵심 컴포넌트
|
||||
|
||||
| 컴포넌트 | 위치 | 역할 |
|
||||
|----------|------|------|
|
||||
| `ActivityLogChannel` | `app/ActivityLog/ActivityLogChannel.php` | Monolog Logger 팩토리 (`config/logging.php`의 `via` 클래스) |
|
||||
| `ActivityLogHandler` | `app/ActivityLog/ActivityLogHandler.php` | Monolog Handler — context에서 데이터 추출 후 DB 저장 |
|
||||
| `ActivityLogProcessor` | `app/ActivityLog/ActivityLogProcessor.php` | Monolog Processor — `user_id`, `ip_address`, `user_agent` 자동 주입 |
|
||||
| `ResolvesActivityLogType` | `app/ActivityLog/Traits/ResolvesActivityLogType.php` | log_type 자동 결정 트레이트 — `Auth::user()` 기반 Admin/User/System 분류 |
|
||||
| `ChangeDetector` | `app/ActivityLog/ChangeDetector.php` | 모델 스냅샷 비교 → 구조화된 변경 이력 생성 |
|
||||
| `CoreActivityLogListener` | `app/Listeners/CoreActivityLogListener.php` | 코어 서비스 훅 구독 리스너 |
|
||||
| `ActivityLog` | `app/Models/ActivityLog.php` | Eloquent 모델 (`localized_description` 접근자 포함) |
|
||||
| `ActivityLogService` | `app/Services/ActivityLogService.php` | **조회 전용** 서비스 (기록 메서드 없음) |
|
||||
|
||||
### config/logging.php 채널 설정
|
||||
|
||||
```php
|
||||
'activity' => [
|
||||
'driver' => 'custom',
|
||||
'via' => \App\ActivityLog\ActivityLogChannel::class,
|
||||
'level' => 'debug',
|
||||
],
|
||||
```
|
||||
|
||||
### config/activity_log.php
|
||||
|
||||
```php
|
||||
return [
|
||||
'enabled' => env('ACTIVITY_LOG_ENABLED', true), // false 시 Handler에서 DB 저장 건너뜀
|
||||
'channel' => env('ACTIVITY_LOG_CHANNEL', 'activity'),
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 로깅 흐름
|
||||
|
||||
### 1단계: Service에서 훅 발행
|
||||
|
||||
Service 계층에서 비즈니스 로직 수행 후 `doAction` 으로 훅을 발행합니다.
|
||||
|
||||
```php
|
||||
// Service 내부 (예: UserService)
|
||||
$this->hookManager->doAction('core.user.after_create', $user, $data);
|
||||
```
|
||||
|
||||
### 2단계: Listener에서 로그 기록
|
||||
|
||||
Listener가 훅을 수신하여 `Log::channel('activity')->info()` 를 호출합니다.
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
public function handleUserAfterCreate(User $user, array $data): void
|
||||
{
|
||||
$this->logActivity('user.create', [
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'loggable' => $user,
|
||||
'description_key' => 'activity_log.description.user_create',
|
||||
'description_params' => ['user_id' => $user->uuid],
|
||||
'properties' => ['email' => $user->email, 'name' => $user->name],
|
||||
]);
|
||||
}
|
||||
|
||||
private function logActivity(string $action, array $context): void
|
||||
{
|
||||
try {
|
||||
Log::channel('activity')->info($action, $context);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Failed to record activity log', [
|
||||
'action' => $action,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3단계: Processor + Handler
|
||||
|
||||
1. **ActivityLogProcessor**: 리스너에서 명시적으로 전달하지 않은 `user_id`, `ip_address`, `user_agent`를 자동 주입
|
||||
2. **ActivityLogHandler**: context에서 구조화 데이터를 추출하여 `ActivityLog::create()` 호출
|
||||
|
||||
### Context 배열 구조
|
||||
|
||||
| 키 | 타입 | 필수 | 설명 |
|
||||
|----|------|------|------|
|
||||
| `log_type` | `ActivityLogType` | O | 로그 유형 (Admin/User/System) |
|
||||
| `loggable` | `Model` | - | 대상 모델 (morph 관계). 삭제 엔티티는 `loggable_type` + `loggable_id` 직접 지정 |
|
||||
| `loggable_type` | `string` | - | `loggable` 대신 morph 타입 직접 지정 (삭제된 엔티티용) |
|
||||
| `loggable_id` | `int` | - | `loggable` 대신 morph ID 직접 지정 (삭제된 엔티티용) |
|
||||
| `description_key` | `string` | O | 다국어 번역 키 |
|
||||
| `description_params` | `array` | - | 번역 파라미터 |
|
||||
| `properties` | `array` | - | 추가 속성 (JSON) |
|
||||
| `changes` | `array` | - | 변경 이력 (ChangeDetector 결과) |
|
||||
| `user_id` | `int` | - | 자동 주입 (Processor) |
|
||||
| `ip_address` | `string` | - | 자동 주입 (Processor) |
|
||||
| `user_agent` | `string` | - | 자동 주입 (Processor, 500자 제한) |
|
||||
|
||||
---
|
||||
|
||||
## Listener 작성 패턴
|
||||
|
||||
### 기본 구조
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Vendor\Module\Listeners;
|
||||
|
||||
use App\ActivityLog\ChangeDetector;
|
||||
use App\ActivityLog\Traits\ResolvesActivityLogType;
|
||||
use App\Contracts\Extension\HookListenerInterface;
|
||||
|
||||
class XxxActivityLogListener implements HookListenerInterface
|
||||
{
|
||||
use ResolvesActivityLogType;
|
||||
|
||||
/** @var array<string, array> 스냅샷 저장소 */
|
||||
private array $snapshots = [];
|
||||
|
||||
public static function getSubscribedHooks(): array
|
||||
{
|
||||
return [
|
||||
// before_update: 스냅샷 캡처 (priority 5 — 다른 리스너보다 먼저 실행)
|
||||
'vendor-module.entity.before_update' => ['method' => 'captureEntitySnapshot', 'priority' => 5],
|
||||
|
||||
// after_xxx: 로그 기록 (priority 20)
|
||||
'vendor-module.entity.after_create' => ['method' => 'handleEntityAfterCreate', 'priority' => 20],
|
||||
'vendor-module.entity.after_update' => ['method' => 'handleEntityAfterUpdate', 'priority' => 20],
|
||||
'vendor-module.entity.after_delete' => ['method' => 'handleEntityAfterDelete', 'priority' => 20],
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(...$args): void
|
||||
{
|
||||
// 개별 메서드에서 처리
|
||||
}
|
||||
|
||||
// ─── 스냅샷 캡처 ───
|
||||
|
||||
public function captureEntitySnapshot(Model $entity, array $data): void
|
||||
{
|
||||
$this->snapshots['entity_' . $entity->id] = $entity->toArray();
|
||||
}
|
||||
|
||||
// ─── 핸들러 ───
|
||||
|
||||
public function handleEntityAfterCreate(Model $entity, array $data): void
|
||||
{
|
||||
// log_type 미지정 시 ResolvesActivityLogType 트레이트가 Auth::user() 기반 자동 결정
|
||||
$this->logActivity('entity.create', [
|
||||
'loggable' => $entity,
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_create',
|
||||
'description_params' => ['entity_name' => $entity->name ?? ''],
|
||||
'properties' => ['id' => $entity->id],
|
||||
]);
|
||||
}
|
||||
|
||||
public function handleEntityAfterUpdate(Model $entity, array $data): void
|
||||
{
|
||||
$snapshot = $this->snapshots['entity_' . $entity->id] ?? null;
|
||||
$changes = ChangeDetector::detect($entity, $snapshot);
|
||||
|
||||
$this->logActivity('entity.update', [
|
||||
'loggable' => $entity,
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_update',
|
||||
'description_params' => ['entity_name' => $entity->name ?? ''],
|
||||
'changes' => $changes,
|
||||
]);
|
||||
|
||||
unset($this->snapshots['entity_' . $entity->id]);
|
||||
}
|
||||
|
||||
public function handleEntityAfterDelete(Model $entity): void
|
||||
{
|
||||
$this->logActivity('entity.delete', [
|
||||
'loggable' => $entity,
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_delete',
|
||||
'description_params' => ['entity_name' => $entity->name ?? ''],
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### ResolvesActivityLogType 트레이트
|
||||
|
||||
모든 ActivityLog 리스너는 `ResolvesActivityLogType` 트레이트를 사용합니다.
|
||||
이 트레이트는 두 가지 메서드를 제공합니다:
|
||||
|
||||
- **`resolveLogType()`** — `Auth::user()` 기반으로 log_type을 동적 결정:
|
||||
- Admin 역할 보유자 → `ActivityLogType::Admin`
|
||||
- 인증된 비관리자 → `ActivityLogType::User`
|
||||
- 비인증(비회원/CLI/시스템) → `ActivityLogType::System`
|
||||
|
||||
- **`logActivity(string $action, array $context)`** — `Log::channel('activity')->info()` 래퍼:
|
||||
- context에 `log_type`이 없으면 `resolveLogType()`으로 자동 주입
|
||||
- try-catch로 로그 실패가 비즈니스 로직을 중단하지 않도록 보호
|
||||
|
||||
**log_type 명시가 필요한 경우** (예: 시스템 자동 작업):
|
||||
|
||||
```php
|
||||
$this->logActivity('schedule.auto_run', [
|
||||
'log_type' => ActivityLogType::System, // 명시 시 auto-resolve 건너뜀
|
||||
'description_key' => 'activity_log.description.schedule_auto_run',
|
||||
]);
|
||||
```
|
||||
|
||||
### 핵심 규칙
|
||||
|
||||
| 규칙 | 설명 |
|
||||
|------|------|
|
||||
| `HookListenerInterface` 구현 필수 | `getSubscribedHooks()` + `handle()` 메서드 |
|
||||
| `use ResolvesActivityLogType` 필수 | 모든 ActivityLog 리스너에 트레이트 적용 |
|
||||
| before_update priority 5 | 다른 리스너보다 먼저 실행하여 변경 전 스냅샷 확보 |
|
||||
| after_xxx priority 20 | 실제 로직 완료 후 기록 |
|
||||
| `log_type` 하드코딩 금지 | 트레이트가 `Auth::user()` 기반으로 자동 결정 (필요 시 명시 가능) |
|
||||
| 스냅샷 사용 후 `unset` | 메모리 누수 방지 |
|
||||
|
||||
---
|
||||
|
||||
## 변경 추적 (ChangeDetector)
|
||||
|
||||
### 모델에 $activityLogFields 정의 (필수)
|
||||
|
||||
> **주의**: ChangeDetector를 호출하는 모든 모델은 `$activityLogFields` 정의 필수입니다.
|
||||
> 미정의 시 `ChangeDetector::detect()` 가 항상 `null` 을 반환하여 changes 컬럼이 빈 채로 기록됩니다.
|
||||
|
||||
추적할 필드를 모델에 `public static array $activityLogFields` 로 선언합니다.
|
||||
|
||||
```php
|
||||
class Product extends Model
|
||||
{
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'name' => [
|
||||
'label_key' => 'sirsoft-ecommerce::product.name',
|
||||
'type' => 'text',
|
||||
],
|
||||
'price' => [
|
||||
'label_key' => 'sirsoft-ecommerce::product.price',
|
||||
'type' => 'currency',
|
||||
],
|
||||
'status' => [
|
||||
'label_key' => 'sirsoft-ecommerce::product.status',
|
||||
'type' => 'enum',
|
||||
'enum' => ProductStatus::class, // Backed Enum 클래스 (labelKey() 메서드 필수)
|
||||
],
|
||||
'is_visible' => [
|
||||
'label_key' => 'sirsoft-ecommerce::product.is_visible',
|
||||
'type' => 'boolean',
|
||||
],
|
||||
'published_at' => [
|
||||
'label_key' => 'sirsoft-ecommerce::product.published_at',
|
||||
'type' => 'datetime',
|
||||
],
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 지원 타입
|
||||
|
||||
| type | 설명 | 비고 |
|
||||
|------|------|------|
|
||||
| `text` | 일반 문자열 | 기본값 (type 생략 시) |
|
||||
| `number` | 숫자 | 정수/실수 |
|
||||
| `currency` | 통화 금액 | 프론트엔드에서 포맷팅 시 사용 |
|
||||
| `date` | 날짜 | Y-m-d |
|
||||
| `datetime` | 날짜+시간 | Y-m-d H:i:s |
|
||||
| `enum` | Enum 값 | `enum` 키에 Backed Enum 클래스 지정 필수 |
|
||||
| `boolean` | 참/거짓 | true/false |
|
||||
| `json` | JSON 데이터 | 객체/배열 |
|
||||
|
||||
### ChangeDetector 사용법
|
||||
|
||||
```php
|
||||
// 1. before_update 훅에서 스냅샷 캡처
|
||||
public function captureSnapshot(Model $model, array $data): void
|
||||
{
|
||||
$this->snapshots['model_' . $model->id] = $model->toArray();
|
||||
}
|
||||
|
||||
// 2. after_update 훅에서 변경 감지
|
||||
public function handleAfterUpdate(Model $model, array $data): void
|
||||
{
|
||||
$snapshot = $this->snapshots['model_' . $model->id] ?? null;
|
||||
$changes = ChangeDetector::detect($model, $snapshot);
|
||||
// $changes 는 null (변경 없음) 또는 변경 배열
|
||||
}
|
||||
```
|
||||
|
||||
### changes 배열 구조
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"field": "status",
|
||||
"label_key": "sirsoft-ecommerce::product.status",
|
||||
"old": "draft",
|
||||
"new": "active",
|
||||
"type": "enum",
|
||||
"old_label_key": "sirsoft-ecommerce::enums.product_status.draft",
|
||||
"new_label_key": "sirsoft-ecommerce::enums.product_status.active"
|
||||
},
|
||||
{
|
||||
"field": "name",
|
||||
"label_key": "sirsoft-ecommerce::product.name",
|
||||
"old": "기존 상품명",
|
||||
"new": "새 상품명",
|
||||
"type": "text"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- `old_label_key` / `new_label_key` 는 `type: "enum"` 일 때만 추가됩니다.
|
||||
- Enum 클래스에 `labelKey(): string` 메서드가 필수입니다.
|
||||
- Backed Enum 값은 자동으로 `->value` 로 변환하여 비교합니다.
|
||||
|
||||
---
|
||||
|
||||
## 다국어 키 규칙
|
||||
|
||||
### 코어
|
||||
|
||||
```text
|
||||
activity_log.description.{entity}_{verb}
|
||||
```
|
||||
|
||||
| 예시 키 | 설명 |
|
||||
|--------|------|
|
||||
| `activity_log.description.user_create` | 사용자 생성 |
|
||||
| `activity_log.description.user_update` | 사용자 수정 |
|
||||
| `activity_log.description.user_delete` | 사용자 삭제 |
|
||||
| `activity_log.description.role_create` | 역할 생성 |
|
||||
| `activity_log.description.settings_save` | 설정 저장 |
|
||||
|
||||
lang 파일 위치: `lang/ko/activity_log.php`, `lang/en/activity_log.php`
|
||||
|
||||
```php
|
||||
// lang/ko/activity_log.php
|
||||
return [
|
||||
'description' => [
|
||||
'user_create' => '회원 :user_id 생성',
|
||||
'user_update' => '회원 :user_id 정보 수정',
|
||||
'user_delete' => '회원 :user_id 삭제',
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
### 모듈
|
||||
|
||||
```text
|
||||
{module-id}::activity_log.description.{entity}_{verb}
|
||||
```
|
||||
|
||||
| 예시 키 | 설명 |
|
||||
|--------|------|
|
||||
| `sirsoft-ecommerce::activity_log.description.order_create` | 주문 생성 |
|
||||
| `sirsoft-page::activity_log.description.page_update` | 페이지 수정 |
|
||||
| `sirsoft-board::activity_log.description.post_delete` | 게시글 삭제 |
|
||||
|
||||
lang 파일 위치: `modules/_bundled/{id}/resources/lang/ko/activity_log.php`
|
||||
|
||||
```php
|
||||
// modules/_bundled/sirsoft-page/resources/lang/ko/activity_log.php
|
||||
return [
|
||||
'description' => [
|
||||
'page_create' => '페이지 ":page_title" 생성',
|
||||
'page_update' => '페이지 ":page_title" 수정',
|
||||
'page_delete' => '페이지 ":page_title" 삭제',
|
||||
'page_publish' => '페이지 ":page_title" 공개',
|
||||
'page_unpublish' => '페이지 ":page_title" 비공개 전환',
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
### 규칙
|
||||
|
||||
- 파라미터는 Laravel 표준 `:param` 문법 사용 (예: `:user_id`, `:page_title`)
|
||||
- `ko` 와 `en` lang 파일 모두 정의 필수
|
||||
- DB에는 번역 키(`description_key`)와 파라미터(`description_params`)만 저장
|
||||
- 실시간 번역은 `ActivityLog::localized_description` 접근자에서 수행
|
||||
|
||||
---
|
||||
|
||||
## description_params 저장 정책
|
||||
|
||||
### 핵심 규칙: ID를 저장하고, 표시 시 이름으로 변환
|
||||
|
||||
`description_params` 에는 표시용 이름이 아닌 **ID** 를 저장합니다.
|
||||
이름 변경 시 과거 로그도 최신 이름으로 표시되어야 하기 때문입니다.
|
||||
|
||||
```php
|
||||
// ✅ 올바른 사용 — ID 저장
|
||||
'description_params' => ['brand_id' => $brand->id],
|
||||
|
||||
// ❌ 금지 — 이름 직접 저장
|
||||
'description_params' => ['brand_name' => $brand->name],
|
||||
```
|
||||
|
||||
### 삭제 시 예외: properties에 이름 스냅샷 보존
|
||||
|
||||
엔티티 삭제 시에는 DB 조회가 불가하므로 `properties` 에 이름 스냅샷을 함께 저장합니다.
|
||||
`ActivityLogDescriptionResolver` 가 `properties.name` 을 우선 사용합니다.
|
||||
|
||||
```php
|
||||
public function handleEntityAfterDelete(Model $entity): void
|
||||
{
|
||||
$this->logActivity('entity.delete', [
|
||||
'loggable' => $entity,
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_delete',
|
||||
'description_params' => ['entity_id' => $entity->id],
|
||||
'properties' => ['name' => $entity->name], // 삭제 후 DB 조회 불가 → 스냅샷 보존
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
### properties vs changes vs description_params 역할 구분
|
||||
|
||||
| 컬럼 | 용도 | 저장 내용 |
|
||||
|------|------|----------|
|
||||
| `description_params` | 번역 키의 `:placeholder` 치환용 | 엔티티 ID (`ActivityLogDescriptionResolver` 가 표시 시 이름으로 변환) |
|
||||
| `changes` | `ChangeDetector` 결과 | 필드별 `old`/`new` 구조화 데이터 (자동 생성) |
|
||||
| `properties` | 추가 메타데이터 | bulk IDs, 삭제 시 이름 스냅샷, 기타 컨텍스트 데이터 |
|
||||
|
||||
---
|
||||
|
||||
## ActivityLogDescriptionResolver 규정
|
||||
|
||||
### 역할
|
||||
|
||||
`core.activity_log.filter_description_params` 필터 훅을 구독하는 리스너입니다.
|
||||
활동 로그에 저장된 엔티티 ID를 **표시 시점에** 사람이 읽을 수 있는 이름으로 변환합니다.
|
||||
|
||||
### 해석 우선순위
|
||||
|
||||
1. **`properties.name` 스냅샷** — 로그 기록 시점의 이름 (삭제된 엔티티도 처리 가능)
|
||||
2. **DB 조회** — `description_params` 의 ID로 모델 조회 → 현재 이름 반환
|
||||
3. **Fallback** — DB 조회 실패 시 `"ID: {id}"` 문자열 반환
|
||||
|
||||
### 모듈별 구현 패턴
|
||||
|
||||
각 모듈은 자체 `ActivityLogDescriptionResolver` 를 구현합니다.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Vendor\Module\Listeners;
|
||||
|
||||
use App\Contracts\Extension\HookListenerInterface;
|
||||
|
||||
class ActivityLogDescriptionResolver implements HookListenerInterface
|
||||
{
|
||||
public static function getSubscribedHooks(): array
|
||||
{
|
||||
return [
|
||||
'core.activity_log.filter_description_params' => [
|
||||
'method' => 'resolveDescriptionParams',
|
||||
'type' => 'filter', // ← Filter 훅 — type 명시 필수
|
||||
'priority' => 10,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function handle(...$args): void
|
||||
{
|
||||
// 기본 핸들러는 사용하지 않음
|
||||
}
|
||||
|
||||
public function resolveDescriptionParams(array $params, string $descriptionKey, array $properties): array
|
||||
{
|
||||
$prefix = 'vendor-module::activity_log.description.';
|
||||
if (! str_starts_with($descriptionKey, $prefix)) {
|
||||
return $params; // 다른 모듈의 키 → 무시
|
||||
}
|
||||
|
||||
$keySuffix = str_replace($prefix, '', $descriptionKey);
|
||||
|
||||
return match (true) {
|
||||
str_starts_with($keySuffix, 'entity_') => $this->resolveEntityName($params, $properties),
|
||||
default => $params,
|
||||
};
|
||||
}
|
||||
|
||||
private function resolveEntityName(array $params, array $properties): array
|
||||
{
|
||||
if (! empty($params['entity_name'])) {
|
||||
return $params; // 이미 해석됨
|
||||
}
|
||||
|
||||
// 1순위: properties.name 스냅샷
|
||||
if (! empty($properties['name'])) {
|
||||
$params['entity_name'] = $properties['name'];
|
||||
return $params;
|
||||
}
|
||||
|
||||
// 2순위: DB 조회
|
||||
$id = $params['entity_id'] ?? null;
|
||||
if ($id) {
|
||||
$entity = Entity::find($id);
|
||||
$params['entity_name'] = $entity?->name ?? "ID: {$id}";
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 등록
|
||||
|
||||
모듈의 `module.php` 에서 `getHookListeners()` 에 등록합니다.
|
||||
|
||||
```php
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [
|
||||
XxxActivityLogListener::class,
|
||||
ActivityLogDescriptionResolver::class, // ← 추가
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 다국어 이름 처리
|
||||
|
||||
이름이 다국어 배열(`['ko' => '한국어', 'en' => 'English']`)인 경우 현재 로케일에 맞게 해석합니다.
|
||||
|
||||
```php
|
||||
private function resolveI18nName(mixed $name): string
|
||||
{
|
||||
if (is_string($name)) {
|
||||
return $name;
|
||||
}
|
||||
if (is_array($name)) {
|
||||
$locale = app()->getLocale();
|
||||
return $name[$locale] ?? $name['ko'] ?? (array_values($name)[0] ?? '');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 모듈 리스너 등록
|
||||
|
||||
모듈의 `module.php` (AbstractModule 상속) 에서 `getHookListeners()` 메서드에 등록합니다.
|
||||
|
||||
```php
|
||||
// modules/_bundled/sirsoft-page/module.php
|
||||
|
||||
namespace Modules\Sirsoft\Page;
|
||||
|
||||
use App\Extension\AbstractModule;
|
||||
use Modules\Sirsoft\Page\Listeners\PageActivityLogListener;
|
||||
|
||||
class Module extends AbstractModule
|
||||
{
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [
|
||||
PageActivityLogListener::class,
|
||||
// 기타 리스너...
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
AbstractModule이 `boot()` 시점에 `HookManager::registerListener()` 를 자동 호출합니다.
|
||||
별도의 `HookManager::registerListener()` 직접 호출은 불필요합니다.
|
||||
|
||||
---
|
||||
|
||||
## 모델별 로그 조회 API 패턴
|
||||
|
||||
특정 모델(상품, 주문 등)에 대한 활동 로그를 조회하는 API 패턴입니다.
|
||||
|
||||
### Controller에 `logs()` 메서드 추가
|
||||
|
||||
```php
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Resources\ActivityLogResource;
|
||||
use App\Services\ActivityLogService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProductController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private ActivityLogService $activityLogService,
|
||||
// ...
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 상품 활동 로그 목록 조회
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param Product $product 대상 상품
|
||||
* @return JsonResponse 로그 목록 응답
|
||||
*/
|
||||
public function logs(Request $request, Product $product): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = [
|
||||
'per_page' => (int) ($request->query('per_page', 10)),
|
||||
'page' => (int) ($request->query('page', 1)),
|
||||
'sort_order' => $request->query('sort_order', 'desc'),
|
||||
];
|
||||
|
||||
$logs = $this->activityLogService->getLogsForModel($product, $filters);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'vendor-module',
|
||||
'messages.entity.logs_fetch_success',
|
||||
ActivityLogResource::collection($logs)->response()->getData(true)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'vendor-module',
|
||||
'messages.entity.logs_fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 라우트 등록
|
||||
|
||||
```php
|
||||
// routes/api.php (모듈)
|
||||
Route::get('products/{product}/logs', [ProductController::class, 'logs']);
|
||||
```
|
||||
|
||||
### 레이아웃 JSON에서 처리로그 탭 구현
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "activity_logs",
|
||||
"endpoint": "/api/admin/vendor-module/products/{{route.id}}/logs",
|
||||
"method": "GET",
|
||||
"autoFetch": false,
|
||||
"params": { "per_page": 10, "page": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Bulk 로깅 패턴 (Per-Item 필수)
|
||||
|
||||
### 핵심 원칙
|
||||
|
||||
> **모든 bulk 작업은 Per-Item 로깅 필수** — 변경된 엔티티 건별로 `loggable_type`/`loggable_id`가 기록되어야 합니다.
|
||||
> N건 일괄 처리 시 N건의 개별 로그가 생성됩니다.
|
||||
|
||||
```text
|
||||
필수: bulk 작업은 Per-Item 개별 로그 기록 (1건 집계 로그 금지)
|
||||
필수: 각 엔티티별 개별 로그 기록 (loggable => $model 또는 loggable_type/loggable_id 직접 지정)
|
||||
```
|
||||
|
||||
### 패턴 1: Bulk Update — Service에서 스냅샷 + 개별 모델 update
|
||||
|
||||
```php
|
||||
// Service 내부
|
||||
public function bulkUpdateStatus(array $ids, string $newStatus): array
|
||||
{
|
||||
$models = Model::whereIn('id', $ids)->get();
|
||||
$snapshots = [];
|
||||
|
||||
foreach ($models as $model) {
|
||||
$snapshots[$model->id] = $model->toArray();
|
||||
$model->update(['status' => $newStatus]);
|
||||
}
|
||||
|
||||
// 훅에 ids + snapshots 전달
|
||||
$this->hookManager->doAction('module.entity.after_bulk_status_update', $ids, count($models), $snapshots);
|
||||
|
||||
return $snapshots;
|
||||
}
|
||||
```
|
||||
|
||||
### 패턴 2: Bulk Update — Listener에서 per-item 로그 기록
|
||||
|
||||
```php
|
||||
public function handleAfterBulkStatusUpdate(array $ids, int $updatedCount, array $snapshots = []): void
|
||||
{
|
||||
$models = Model::whereIn('id', $ids)->get()->keyBy('id');
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$model = $models->get($id);
|
||||
if (! $model) {
|
||||
continue; // 존재하지 않는 ID는 건너뜀
|
||||
}
|
||||
|
||||
$snapshot = $snapshots[$id] ?? null;
|
||||
$changes = $snapshot ? ChangeDetector::detect($model, $snapshot) : null;
|
||||
|
||||
$this->logActivity('entity.bulk_status_update', [
|
||||
'loggable' => $model, // ← 개별 모델 지정 필수
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_status_update',
|
||||
'description_params' => ['entity_id' => $id],
|
||||
'changes' => $changes,
|
||||
'properties' => ['entity_id' => $id],
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 패턴 3: Bulk Delete — 삭제된 엔티티의 per-item 로깅
|
||||
|
||||
엔티티가 이미 삭제되어 DB 조회가 불가한 경우, `loggable_type`/`loggable_id`를 직접 지정합니다.
|
||||
`ActivityLogHandler`가 `loggable` 모델이 없을 때 이 값을 fallback으로 사용합니다.
|
||||
|
||||
```php
|
||||
public function handleAfterBulkDelete(array $ids, int $deletedCount, array $snapshots = []): void
|
||||
{
|
||||
foreach ($ids as $id) {
|
||||
$snapshot = $snapshots[$id] ?? null;
|
||||
|
||||
$this->logActivity('entity.bulk_delete', [
|
||||
'loggable_type' => Model::class, // ← morph 타입 직접 지정
|
||||
'loggable_id' => $id, // ← morph ID 직접 지정
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_delete',
|
||||
'description_params' => ['entity_id' => $id],
|
||||
'properties' => [
|
||||
'entity_id' => $id,
|
||||
'snapshot' => $snapshot, // 삭제 전 데이터 보존
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 패턴 4: Bulk Toggle — 모델 조회 후 per-item 로깅
|
||||
|
||||
```php
|
||||
public function handleAfterBulkToggleActive(array $ids, bool $isActive, int $count, array $snapshots = []): void
|
||||
{
|
||||
$models = Model::whereIn('id', $ids)->get()->keyBy('id');
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$model = $models->get($id);
|
||||
if (! $model) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$snapshot = $snapshots[$id] ?? null;
|
||||
$changes = $snapshot ? ChangeDetector::detect($model, $snapshot) : null;
|
||||
|
||||
$this->logActivity('entity.bulk_toggle_active', [
|
||||
'loggable' => $model,
|
||||
'description_key' => 'vendor-module::activity_log.description.entity_toggle_active',
|
||||
'description_params' => ['entity_id' => $id],
|
||||
'changes' => $changes,
|
||||
'properties' => ['entity_id' => $id, 'is_active' => $isActive],
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### loggable vs loggable_type/loggable_id 선택 기준
|
||||
|
||||
| 상황 | 사용 방식 |
|
||||
| --- | --- |
|
||||
| 모델이 존재함 (update/toggle) | `'loggable' => $model` |
|
||||
| 모델이 삭제됨 (delete) | `'loggable_type' => Model::class, 'loggable_id' => $id` |
|
||||
| 두 값 모두 존재 시 | `loggable` 우선 (Handler에서 `loggable instanceof Model` 체크) |
|
||||
|
||||
### 삭제 작업 ChangeDetector
|
||||
|
||||
bulk delete 는 변경 전후 비교가 불필요하므로 ChangeDetector를 사용하지 않습니다.
|
||||
대신 `properties.snapshot` 에 삭제 전 데이터를 보존합니다.
|
||||
|
||||
---
|
||||
|
||||
## DB 스키마
|
||||
|
||||
### activity_logs 테이블
|
||||
|
||||
| 컬럼 | 타입 | Nullable | 설명 |
|
||||
|------|------|----------|------|
|
||||
| `id` | bigint (PK) | N | 활동 로그 ID |
|
||||
| `log_type` | varchar(20) | N | 로그 유형 (admin/user/system) |
|
||||
| `loggable_type` | varchar | Y | 대상 모델 morph 타입 |
|
||||
| `loggable_id` | bigint | Y | 대상 모델 ID |
|
||||
| `user_id` | bigint (FK) | Y | 행위자 사용자 ID (삭제 시 NULL) |
|
||||
| `action` | varchar(50) | N | 액션 유형 (예: user.create, page.update) |
|
||||
| `description_key` | varchar(150) | Y | 다국어 번역 키 |
|
||||
| `description_params` | json | Y | 다국어 번역 파라미터 |
|
||||
| `properties` | json | Y | 추가 속성 데이터 |
|
||||
| `changes` | json | Y | 구조화된 변경 이력 (ChangeDetector 결과) |
|
||||
| `ip_address` | varchar(45) | Y | IP 주소 (IPv6 대응) |
|
||||
| `user_agent` | varchar(500) | Y | User Agent (500자 제한) |
|
||||
| `created_at` | timestamp | N | 생성일시 (updated_at 없음) |
|
||||
|
||||
- `timestamps = false` — `created_at` 만 사용 (boot 시 자동 설정)
|
||||
- `user_id` 는 `nullOnDelete` — 사용자 삭제 시 NULL 처리
|
||||
|
||||
---
|
||||
|
||||
## 인덱스
|
||||
|
||||
### 단일 인덱스
|
||||
|
||||
| 컬럼 | 용도 |
|
||||
|------|------|
|
||||
| `log_type` | 유형별 필터링 |
|
||||
| `user_id` | 사용자별 조회 |
|
||||
| `action` | 액션별 필터링 |
|
||||
| `created_at` | 시간순 정렬/범위 조회 |
|
||||
| `loggable_type` + `loggable_id` | morphs 자동 생성 인덱스 |
|
||||
|
||||
### 복합 인덱스
|
||||
|
||||
| 인덱스명 | 컬럼 | 용도 |
|
||||
|----------|------|------|
|
||||
| `idx_activity_logs_loggable` | (`loggable_type`, `loggable_id`, `created_at`) | 특정 모델의 로그 시간순 조회 |
|
||||
| `idx_activity_logs_type_action_date` | (`log_type`, `action`, `created_at`) | 유형+액션 기반 필터링 |
|
||||
|
||||
---
|
||||
|
||||
## 금지 사항
|
||||
|
||||
| 금지 | 올바른 사용 |
|
||||
|------|-------------|
|
||||
| `ActivityLogService->log()` / `logAdmin()` / `logUser()` / `logSystem()` | 제거됨 — `Log::channel('activity')->info()` 사용 |
|
||||
| `ActivityLogManager` / `Driver` 패턴 | 제거됨 — Monolog 기반 아키텍처로 전환 |
|
||||
| Controller에서 직접 로그 기록 | Listener에서만 기록 (Service 훅 → Listener → Log) |
|
||||
| description 컬럼에 번역된 텍스트 저장 | `description_key` + `description_params` 사용 |
|
||||
| ActivityLogService를 기록용으로 사용 | 조회 전용 — 기록은 `Log::channel('activity')` |
|
||||
| Listener 밖에서 `ActivityLog::create()` 직접 호출 | `Log::channel('activity')` 를 통해 기록 (Processor 자동 주입 보장) |
|
||||
| `$activityLogFields` 미정의 상태에서 ChangeDetector 호출 | ChangeDetector를 사용하는 모든 모델에 `$activityLogFields` 정의 필수 |
|
||||
| `description_params` 에 표시용 이름 직접 저장 | ID 저장 + `ActivityLogDescriptionResolver` 에서 표시 시 변환 |
|
||||
| 별도 로그 테이블/서비스 운영 (예: `ecommerce_product_logs`) | `activity_logs` 단일 테이블로 통합 |
|
||||
| Bulk 작업을 1건의 집계 로그로 기록 (loggable 없이 count만 저장) | Per-Item: 변경된 각 엔티티별 개별 로그 기록 필수 |
|
||||
| Bulk delete에서 loggable 미지정 | `loggable_type` + `loggable_id` 직접 지정 (삭제 엔티티 대응) |
|
||||
|
||||
---
|
||||
|
||||
## 참고 파일
|
||||
|
||||
| 파일 | 경로 |
|
||||
|------|------|
|
||||
| ActivityLogChannel | `app/ActivityLog/ActivityLogChannel.php` |
|
||||
| ActivityLogHandler | `app/ActivityLog/ActivityLogHandler.php` |
|
||||
| ActivityLogProcessor | `app/ActivityLog/ActivityLogProcessor.php` |
|
||||
| ChangeDetector | `app/ActivityLog/ChangeDetector.php` |
|
||||
| CoreActivityLogListener | `app/Listeners/CoreActivityLogListener.php` |
|
||||
| ActivityLog 모델 | `app/Models/ActivityLog.php` |
|
||||
| ActivityLogService | `app/Services/ActivityLogService.php` |
|
||||
| ActivityLogType Enum | `app/Enums/ActivityLogType.php` |
|
||||
| config/activity_log.php | `config/activity_log.php` |
|
||||
| config/logging.php (activity 채널) | `config/logging.php` |
|
||||
| 마이그레이션 (생성) | `database/migrations/2026_04_01_000027_create_activity_logs_table.php` |
|
||||
| 마이그레이션 (i18n 전환) | `database/migrations/2026_04_01_000657_update_i18n_fields_in_activity_logs_table.php` |
|
||||
|
||||
---
|
||||
|
||||
## 개발자 체크리스트
|
||||
|
||||
### 새 모델 추가 시
|
||||
|
||||
```text
|
||||
□ 모델에 public static array $activityLogFields 정의
|
||||
□ ActivityLogListener에 before_update (스냅샷 캡처) + after_create/update/delete 훅 등록
|
||||
□ description_params에 ID 저장 (이름 직접 저장 금지)
|
||||
□ ActivityLogDescriptionResolver에 해당 모델의 ID→이름 해석 로직 추가
|
||||
□ lang/{ko,en}/activity_log.php에 description 키 추가
|
||||
□ (선택) Controller에 logs() 메서드 + 라우트 추가 (모델별 로그 조회 필요 시)
|
||||
```
|
||||
|
||||
### CRUD 훅 추가 시
|
||||
|
||||
```text
|
||||
□ before_update 훅: priority 5 (스냅샷 캡처용)
|
||||
□ after_xxx 훅: priority 20 (로그 기록)
|
||||
□ update 핸들러에서 ChangeDetector::detect() 호출
|
||||
□ delete 핸들러에서 properties에 이름 스냅샷 보존
|
||||
□ ko/en 다국어 키 모두 추가
|
||||
```
|
||||
|
||||
### Bulk Update 추가 시
|
||||
|
||||
```text
|
||||
□ Service: 변경 전 모델을 일괄 로드 (whereIn()->get())
|
||||
□ Service: 각 모델별 toArray() 스냅샷 캡처 → $snapshots 배열
|
||||
□ Service: 개별 모델 update 실행
|
||||
□ Service: 훅에 $ids + $count + $snapshots 전달
|
||||
□ Listener: per-item 루프 — 각 ID별 모델 조회 + ChangeDetector + 개별 logActivity 호출
|
||||
□ Listener: 존재하지 않는 ID는 continue로 건너뜀
|
||||
□ 1건의 집계 로그가 아닌, N건의 개별 로그 생성 확인
|
||||
□ 각 로그에 loggable => $model (또는 loggable_type/loggable_id) 포함 확인
|
||||
□ ko/en 다국어 키 모두 추가
|
||||
□ 테스트: N건 처리 시 N건 로그 생성 검증 + loggable 정확성 검증
|
||||
```
|
||||
|
||||
### Bulk Delete 추가 시
|
||||
|
||||
```text
|
||||
□ Service: 삭제 전 스냅샷 캡처 → $snapshots 배열 (keyBy id)
|
||||
□ Service: 훅에 $ids + $count + $snapshots 전달
|
||||
□ Listener: per-item 루프 — 각 ID별 loggable_type/loggable_id 직접 지정
|
||||
□ Listener: properties.snapshot에 삭제 전 데이터 보존
|
||||
□ 테스트: loggable_type/loggable_id 정확성 검증
|
||||
```
|
||||
@@ -0,0 +1,504 @@
|
||||
# API 리소스
|
||||
|
||||
> **목적**: API 응답 데이터 변환을 위한 리소스 클래스 규칙
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. BaseApiResource 상속 필수
|
||||
2. 민감 정보 제외: created_by, updated_by, deleted_at
|
||||
3. 관계 데이터: whenLoaded() 사용
|
||||
4. when() 주의: 커스텀 메서드에서는 삼항 연산자 사용 (MissingValue 누출 방지)
|
||||
5. 권한 메타: ...$this->resourceMeta($request) 스프레드로 is_owner + abilities(can_*) 표준화
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [기본 규칙](#기본-규칙)
|
||||
2. [권한 메타 표준화 (is_owner + abilities)](#권한-메타-표준화-is_owner--abilities)
|
||||
3. [$this->when() 사용 주의사항](#thiswhen-사용-주의사항)
|
||||
4. [패턴 예시](#패턴-예시)
|
||||
|
||||
---
|
||||
|
||||
## 기본 규칙
|
||||
|
||||
### BaseApiResource 상속 필수
|
||||
|
||||
모든 API 리소스는 `BaseApiResource`를 상속해야 합니다.
|
||||
|
||||
```php
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
|
||||
class ProductResource extends BaseApiResource
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 민감한 정보 제외
|
||||
|
||||
보안을 위해 다음 필드는 API 응답에서 제외합니다:
|
||||
|
||||
- `created_by` - 생성자 ID
|
||||
- `updated_by` - 수정자 ID
|
||||
- `deleted_at` - 삭제 시간
|
||||
- 비밀번호, 토큰 등 인증 정보
|
||||
|
||||
### 관계 데이터 처리
|
||||
|
||||
관계 데이터는 `whenLoaded`를 사용하여 조건부로 포함합니다:
|
||||
|
||||
```php
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
// ✅ 관계가 로드된 경우에만 포함
|
||||
'category' => new CategoryResource($this->whenLoaded('category')),
|
||||
'images' => ProductImageResource::collection($this->whenLoaded('images')),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 권한 메타 표준화 (is_owner + abilities)
|
||||
|
||||
모든 API 리소스 응답에 `is_owner`와 `abilities` (can_*) 필드를 표준화합니다.
|
||||
|
||||
### 기본 사용법
|
||||
|
||||
`toArray()` 마지막에 `...$this->resourceMeta($request)`를 스프레드합니다:
|
||||
|
||||
```php
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
// ... 기타 필드
|
||||
|
||||
// ✅ 표준 권한 메타 (is_owner + abilities)
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 응답 형식
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"name": "상품명",
|
||||
"is_owner": true,
|
||||
"abilities": {
|
||||
"can_update": true,
|
||||
"can_delete": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `is_owner`: 현재 요청 사용자가 리소스 소유자인지 여부 (`ownerField()` 미정의 시 생략)
|
||||
- `abilities`: `can_*` 키로 통합된 권한 플래그 (`abilityMap()` 미정의 시 생략)
|
||||
|
||||
### ownerField() — 소유자 판단
|
||||
|
||||
리소스의 소유자 필드명을 반환합니다:
|
||||
|
||||
```php
|
||||
// 기본값: null (is_owner 생략)
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id'; // 또는 'created_by' 등
|
||||
}
|
||||
```
|
||||
|
||||
### abilityMap() — 정적 권한 매핑
|
||||
|
||||
권한 식별자를 `can_*` 키로 매핑합니다. 대부분의 리소스에서 사용합니다:
|
||||
|
||||
```php
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'sirsoft-ecommerce.products.create',
|
||||
'can_update' => 'sirsoft-ecommerce.products.update',
|
||||
'can_delete' => 'sirsoft-ecommerce.products.delete',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### resolveAbilities() — 동적 권한 (고급)
|
||||
|
||||
slug 기반 동적 식별자가 필요한 경우 `resolveAbilities()`를 오버라이드합니다:
|
||||
|
||||
```php
|
||||
// Board 모듈 PostResource 패턴
|
||||
protected function resolveAbilities(Request $request): array
|
||||
{
|
||||
$slug = $this->getSlug($request);
|
||||
if (! $slug) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$abilityMap = $this->isAdminRequest($request)
|
||||
? [
|
||||
'can_read' => "sirsoft-board.{$slug}.admin.posts.read",
|
||||
'can_write' => "sirsoft-board.{$slug}.admin.posts.write",
|
||||
]
|
||||
: [
|
||||
'can_read' => "sirsoft-board.{$slug}.posts.read",
|
||||
'can_write' => "sirsoft-board.{$slug}.posts.write",
|
||||
];
|
||||
|
||||
return $this->resolveAbilitiesFromMap($abilityMap, $request->user());
|
||||
}
|
||||
```
|
||||
|
||||
### HasAbilityCheck 트레이트
|
||||
|
||||
`BaseApiResource`와 `ResourceCollection` 모두에서 권한 체크 로직을 공유하기 위한 트레이트입니다:
|
||||
|
||||
```php
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
|
||||
// ResourceCollection에서 컬렉션 레벨 abilities 제공
|
||||
class BrandCollection extends ResourceCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'sirsoft-ecommerce.brands.create',
|
||||
'can_update' => 'sirsoft-ecommerce.brands.update',
|
||||
'can_delete' => 'sirsoft-ecommerce.brands.delete',
|
||||
];
|
||||
}
|
||||
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => BrandResource::collection($this->collection),
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 커스텀 메서드에서의 사용
|
||||
|
||||
`toListArray()` 등 커스텀 메서드에서도 동일하게 스프레드합니다:
|
||||
|
||||
```php
|
||||
public function toListArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
|
||||
// ✅ 커스텀 메서드에서도 동일 패턴
|
||||
...$this->resourceMeta(request()),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 권한 체크 및 scope 기반 abilities
|
||||
|
||||
`resolveAbilitiesFromMap()`은 각 ability에 대해 다음 순서로 확인합니다:
|
||||
|
||||
1. 권한 체크 (`PermissionHelper::check()`)
|
||||
2. scope 기반 접근 체크 (`PermissionHelper::checkScopeAccess()`) — 리소스 모델이 있는 경우
|
||||
|
||||
scope_type에 따라 리소스 소유자 기반으로 ability가 자동 제한됩니다. 별도의 바이패스 맵 정의가 불필요합니다.
|
||||
|
||||
> 상세: [permissions.md](../extension/permissions.md) scope_type 시스템 참조
|
||||
|
||||
---
|
||||
|
||||
## $this->when() 사용 주의사항
|
||||
|
||||
```text
|
||||
필수: 커스텀 메서드에서는 삼항 연산자 사용 ($this->when() 금지)
|
||||
필수: 커스텀 메서드에서는 삼항 연산자 사용
|
||||
```
|
||||
|
||||
### 문제 원인
|
||||
|
||||
Laravel의 `$this->when()` 메서드는 조건이 false일 때 `MissingValue` 객체를 반환합니다. 이 객체는 **Laravel이 `toArray()`를 처리할 때만 자동으로 필터링**됩니다. `toListArray()`, `withAdminInfo()` 등 커스텀 메서드에서는 필터링되지 않아 빈 객체 `{}`가 JSON 응답에 포함됩니다.
|
||||
|
||||
### 발생하는 문제
|
||||
|
||||
- React Error #31: "Objects are not valid as a React child"
|
||||
- 프론트엔드에서 빈 화면 표시
|
||||
- 데이터 바인딩 실패
|
||||
|
||||
### 잘못된 예시 (❌ DON'T)
|
||||
|
||||
```php
|
||||
// ❌ 커스텀 메서드에서 $this->when() 사용 - MissingValue 객체 누출
|
||||
public function toListArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
// ❌ email_verified_at이 null이면 빈 객체 {} 반환
|
||||
'email_verified_at' => $this->when(
|
||||
$this->getValue('email_verified_at'),
|
||||
fn () => $this->formatDateTimeStringForUser($this->getValue('email_verified_at'))
|
||||
),
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 올바른 예시 (✅ DO)
|
||||
|
||||
```php
|
||||
// ✅ 커스텀 메서드에서는 삼항 연산자 사용
|
||||
public function toListArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
// ✅ null 반환으로 안전하게 처리
|
||||
'email_verified_at' => $this->getValue('email_verified_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('email_verified_at'))
|
||||
: null,
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 사용 가능/금지 장소
|
||||
|
||||
| 장소 | $this->when() 사용 |
|
||||
|------|-------------------|
|
||||
| `toArray()` 메서드 내부 | ✅ 가능 (Laravel이 MissingValue 자동 필터링) |
|
||||
| `toListArray()` 등 커스텀 메서드 | ❌ 금지 |
|
||||
| `toProfileArray()` 등 커스텀 메서드 | ❌ 금지 |
|
||||
| `withAdminInfo()` 등 추가 정보 메서드 | ❌ 금지 |
|
||||
| `toArray()` 외부에서 수동 호출되는 모든 메서드 | ❌ 금지 |
|
||||
|
||||
### PHPDoc 작성 권장
|
||||
|
||||
커스텀 메서드임을 명시하여 주의사항을 알립니다:
|
||||
|
||||
```php
|
||||
/**
|
||||
* 목록용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
*/
|
||||
public function toListArray(): array
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 패턴 예시
|
||||
|
||||
### 기본 리소스 클래스
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
|
||||
class ProductResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return array
|
||||
*/
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'price' => $this->price,
|
||||
'is_active' => $this->is_active,
|
||||
'category' => new CategoryResource($this->whenLoaded('category')),
|
||||
'images' => ProductImageResource::collection($this->whenLoaded('images')),
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'updated_at' => $this->updated_at?->toISOString(),
|
||||
// created_by, updated_by는 제외 (보안)
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 커스텀 메서드가 있는 리소스
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
class UserResource extends BaseApiResource
|
||||
{
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
// ✅ toArray() 내부에서는 when() 사용 가능
|
||||
'role' => $this->when($this->role, fn () => $this->role->name),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록용 간단한 배열 반환
|
||||
*
|
||||
* 주의: $this->when() 대신 삼항 연산자 사용
|
||||
*/
|
||||
public function toListArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
// ✅ 삼항 연산자 사용
|
||||
'email_verified' => $this->getValue('email_verified_at') ? true : false,
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ResourceCollection 커스텀 메서드
|
||||
|
||||
ResourceCollection에 커스텀 메서드를 추가하여 다양한 응답 형식을 지원할 수 있습니다.
|
||||
|
||||
### 패턴
|
||||
|
||||
```php
|
||||
class UserCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 통계 정보를 추가하여 반환
|
||||
*
|
||||
* @param array $statistics 통계 데이터
|
||||
* @return array
|
||||
*/
|
||||
public function withStatistics(array $statistics): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection,
|
||||
'statistics' => $statistics,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자용 추가 정보를 포함하여 반환
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function withAdminInfo(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection,
|
||||
'meta' => [
|
||||
'total' => $this->total(),
|
||||
'admin_info' => true,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 컨트롤러에서 사용
|
||||
|
||||
```php
|
||||
public function index(UserListRequest $request): JsonResponse
|
||||
{
|
||||
$users = $this->userService->getPaginatedUsers($request->validated());
|
||||
$statistics = $this->userService->getStatistics();
|
||||
$collection = new UserCollection($users);
|
||||
|
||||
return $this->success(
|
||||
'user.fetch_success',
|
||||
$collection->withStatistics($statistics)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 주요 커스텀 메서드 유형
|
||||
|
||||
| 메서드 | 용도 | 반환 데이터 |
|
||||
| ------ | ------ | ------ |
|
||||
| `withStatistics()` | 통계 데이터 추가 | data + statistics |
|
||||
| `withAdminInfo()` | 관리자 전용 메타 추가 | data + admin meta |
|
||||
| `toListArray()` | 목록 전용 간소화 응답 | 축소된 필드 |
|
||||
| `toSimpleArray()` | 최소 필드 응답 | id + name만 |
|
||||
|
||||
### Resource에서 다중 응답 형식
|
||||
|
||||
Resource 클래스에서도 메서드별로 다른 응답 형식을 제공할 수 있습니다:
|
||||
|
||||
```php
|
||||
class UserResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 목록용 간소화 응답
|
||||
*/
|
||||
public function toListArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
'status' => $this->status,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로필용 응답
|
||||
*/
|
||||
public function toProfileArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
'avatar' => $this->avatar_url,
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 리소스 개발 체크리스트
|
||||
|
||||
```text
|
||||
□ BaseApiResource를 상속했는가?
|
||||
□ 민감한 정보(created_by, updated_by, deleted_at)를 제외했는가?
|
||||
□ 관계 데이터에 whenLoaded()를 사용했는가?
|
||||
□ 커스텀 메서드에서 $this->when() 사용을 피했는가?
|
||||
□ 커스텀 메서드에서 삼항 연산자를 사용했는가?
|
||||
□ 날짜 필드에 toISOString()을 사용했는가?
|
||||
□ ...$this->resourceMeta($request) 스프레드를 추가했는가?
|
||||
□ ownerField()를 정의했는가? (소유자 판단 필요 시)
|
||||
□ abilityMap()을 정의했는가? (권한 플래그 필요 시)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [index.md](./index.md) - 백엔드 가이드 인덱스
|
||||
- [controllers.md](./controllers.md) - 컨트롤러에서 리소스 사용
|
||||
- [response-helper.md](./response-helper.md) - API 응답 규칙
|
||||
- [service-repository.md](./service-repository.md) - Eager Loading으로 N+1 방지
|
||||
@@ -0,0 +1,332 @@
|
||||
# 인증 및 세션 처리
|
||||
|
||||
> **관련 문서**: [index.md](index.md) | [middleware.md](middleware.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. Laravel Sanctum 토큰 전용 인증 (Bearer 토큰만 사용)
|
||||
2. 세션은 /dev 대시보드 전용: StartApiSession 미들웨어로 로그인/로그아웃 라우트에서만 생성
|
||||
3. 로그아웃: 토큰 삭제 + 세션 무효화 (세션 존재 시)
|
||||
4. 슬라이딩 만료: 토큰 잔여시간 절반 미만 시 자동 갱신
|
||||
5. 401 응답 시 세션 쿠키 자동 정리 (무조건적 forget cookie)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [Laravel Sanctum 토큰 전용 인증](#laravel-sanctum-토큰-전용-인증)
|
||||
2. [StartApiSession 미들웨어](#startapisession-미들웨어)
|
||||
3. [토큰 슬라이딩 만료](#토큰-슬라이딩-만료)
|
||||
4. [로그아웃 구현 원칙](#로그아웃-구현-원칙)
|
||||
5. [401 응답 시 세션 쿠키 정리](#401-응답-시-세션-쿠키-정리)
|
||||
6. [Laravel Sanctum plainTextToken 구조](#laravel-sanctum-plaintexttoken-구조)
|
||||
7. [세션 존재 확인](#세션-존재-확인)
|
||||
8. [세션 무효화 3단계](#세션-무효화-3단계)
|
||||
9. [완전한 로그아웃 구현 예시](#완전한-로그아웃-구현-예시)
|
||||
10. [안티 패턴](#안티-패턴)
|
||||
|
||||
---
|
||||
|
||||
## Laravel Sanctum 토큰 전용 인증
|
||||
|
||||
그누보드7 프로젝트는 SPA(Single Page Application)를 위한 **토큰 전용 인증 방식**을 사용합니다:
|
||||
|
||||
**특징**:
|
||||
- **Bearer 토큰 전용**: API 인증은 `Authorization: Bearer {token}` 헤더로만 수행
|
||||
- **`EnsureFrontendRequestsAreStateful` 미사용**: 세션 기반 Sanctum Guard를 사용하지 않음
|
||||
- **`currentAccessToken()`**: 항상 `PersonalAccessToken` 반환 (TransientToken 없음)
|
||||
- **세션은 /dev 대시보드 전용**: `StartApiSession` 미들웨어가 로그인/로그아웃 라우트에서만 세션 생성
|
||||
|
||||
**인증 가드 설정** (`bootstrap/app.php`):
|
||||
```php
|
||||
// stateful 미들웨어 없음 — Sanctum Guard는 토큰만 체크
|
||||
$middleware->alias([
|
||||
'start.api.session' => \App\Http\Middleware\StartApiSession::class,
|
||||
]);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## StartApiSession 미들웨어
|
||||
|
||||
로그인/로그아웃 라우트에서만 세션을 시작하는 전용 미들웨어입니다.
|
||||
|
||||
**목적**:
|
||||
- `/dev` 대시보드(Telescope, Horizon 등)는 세션 기반 `web` guard 인증 사용
|
||||
- API 로그인 시 `Auth::guard('web')->login($user)`으로 세션에 사용자 저장
|
||||
- 로그아웃 시 세션 무효화
|
||||
|
||||
**동작 방식**:
|
||||
```php
|
||||
// StartApiSession은 세션 파이프라인만 실행 (CSRF 검증 없음, sanctum 속성 미설정)
|
||||
EncryptCookies → AddQueuedCookiesToResponse → StartSession → Controller
|
||||
```
|
||||
|
||||
**적용 라우트**:
|
||||
```php
|
||||
// 로그인 라우트 (세션 생성)
|
||||
Route::post('login', ...)->middleware('start.api.session');
|
||||
|
||||
// 로그아웃 라우트 (세션 무효화)
|
||||
Route::post('logout', ...)->middleware('start.api.session');
|
||||
```
|
||||
|
||||
**핵심 차이** — `stateful` vs `start.api.session`:
|
||||
|
||||
| 항목 | `stateful` (제거됨) | `start.api.session` |
|
||||
|------|---------------------|---------------------|
|
||||
| 적용 범위 | 모든 API 라우트 | 로그인/로그아웃만 |
|
||||
| Sanctum 세션 인증 | ✅ 활성화 | ❌ 비활성화 |
|
||||
| CSRF 검증 | ✅ 포함 | ❌ 미포함 |
|
||||
| `sanctum` 속성 설정 | ✅ 설정 | ❌ 미설정 |
|
||||
| 세션 쿠키 발급 | 모든 API 응답 | 로그인/로그아웃 응답만 |
|
||||
|
||||
**구현 파일**: `app/Http/Middleware/StartApiSession.php`
|
||||
|
||||
---
|
||||
|
||||
## 토큰 슬라이딩 만료
|
||||
|
||||
G7은 **슬라이딩 만료(Sliding Expiration)** 방식으로 토큰 만료 시간을 자동 갱신합니다.
|
||||
|
||||
### 동작 원리
|
||||
|
||||
```
|
||||
[로그인] ───────────────────────────────────────> [만료]
|
||||
0분 60분
|
||||
↑
|
||||
30분에 API 요청 발생 (절반 미만 남음)
|
||||
│
|
||||
└─────────────────────────────────────> [만료]
|
||||
30분 90분
|
||||
```
|
||||
|
||||
### 갱신 조건
|
||||
|
||||
토큰 만료 시간은 다음 조건을 **모두** 만족할 때 갱신됩니다:
|
||||
|
||||
| 조건 | 설명 |
|
||||
|------|------|
|
||||
| 인증된 요청 | `$request->user()`가 존재 |
|
||||
| PersonalAccessToken | 세션이 아닌 토큰 인증 |
|
||||
| 만료 시간 설정됨 | `expires_at`이 null이 아님 (무한대 토큰 제외) |
|
||||
| 절반 미만 남음 | 잔여 시간 < 설정값의 50% |
|
||||
|
||||
### 설정값
|
||||
|
||||
환경설정의 `security.auth_token_lifetime` 값을 사용합니다:
|
||||
- **기본값**: 30분
|
||||
- **범위**: 0~3600분 (0은 무한대)
|
||||
|
||||
### 구현 파일
|
||||
|
||||
- **미들웨어**: `app/Http/Middleware/RefreshTokenExpiration.php`
|
||||
- **등록 위치**: `bootstrap/app.php` (`api` 그룹에 등록)
|
||||
- **테스트**: `tests/Feature/Api/Auth/TokenExpirationTest.php`
|
||||
|
||||
---
|
||||
|
||||
## 로그아웃 구현 원칙
|
||||
|
||||
```
|
||||
필수: 토큰 삭제 + 세션 무효화 (세션이 존재하는 경우)
|
||||
필수: currentAccessToken() 삭제 → 세션 존재 시 세션 무효화
|
||||
```
|
||||
|
||||
토큰 전용 인증에서는 `currentAccessToken()`이 항상 `PersonalAccessToken`을 반환합니다:
|
||||
|
||||
```php
|
||||
// 1. 토큰 삭제
|
||||
$token = $user->currentAccessToken();
|
||||
if ($token instanceof \Laravel\Sanctum\PersonalAccessToken) {
|
||||
$token->delete();
|
||||
}
|
||||
|
||||
// 2. 세션 무효화 (StartApiSession 미들웨어가 세션을 시작한 경우)
|
||||
if (request()->hasSession() && request()->session()->isStarted() && Auth::guard('web')->check()) {
|
||||
Auth::guard('web')->logout();
|
||||
request()->session()->invalidate();
|
||||
request()->session()->regenerateToken();
|
||||
}
|
||||
```
|
||||
|
||||
**특징**:
|
||||
|
||||
- `stateful` 미들웨어 제거로 `TransientToken` 케이스가 없어짐
|
||||
- `currentAccessToken()`이 항상 `PersonalAccessToken` 반환
|
||||
- 세션 무효화는 `start.api.session` 미들웨어가 적용된 로그아웃 라우트에서만 실행됨
|
||||
|
||||
---
|
||||
|
||||
## 401 응답 시 세션 쿠키 정리
|
||||
|
||||
API 요청에서 `AuthenticationException` 발생 시 (토큰 만료, 미인증 등), 잔존 세션 쿠키를 만료시켜 보안 공백을 방지합니다.
|
||||
|
||||
**구현 위치**: `bootstrap/app.php` `withExceptions()`
|
||||
|
||||
```php
|
||||
$exceptions->render(function (\Illuminate\Auth\AuthenticationException $e, \Illuminate\Http\Request $request) {
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['message' => __('auth.unauthenticated')], 401)
|
||||
->withCookie(cookie()->forget(config('session.cookie')));
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**동작 방식**:
|
||||
|
||||
- **무조건적 forget**: 세션 쿠키 존재 여부와 관계없이 항상 `Set-Cookie` 만료 헤더 전송
|
||||
- 클라이언트에 해당 쿠키가 없으면 `Set-Cookie` 헤더는 무시됨 (무해)
|
||||
- 클라이언트에 잔존 세션 쿠키가 있으면 즉시 삭제됨
|
||||
|
||||
**테스트 파일**: `tests/Feature/Api/Auth/SessionCleanupOnUnauthorizedTest.php`
|
||||
|
||||
---
|
||||
|
||||
## Laravel Sanctum plainTextToken 구조
|
||||
|
||||
**형식**: `{tokenId}|{actualToken}`
|
||||
|
||||
**예시**:
|
||||
```
|
||||
9|iHzLc0VcFxEKi8dJlyqaPQoMBKBgs1ocpZpWKQzj0aaddebe
|
||||
↓ ↓
|
||||
DB ID SHA256 해시 후 DB 저장
|
||||
```
|
||||
|
||||
**DB 저장 방식**:
|
||||
- `|` 앞부분 (tokenId): DB의 `id` 컬럼에 저장
|
||||
- `|` 뒷부분 (actualToken): SHA256 해시 후 `token` 컬럼에 저장
|
||||
|
||||
**파싱 방법**:
|
||||
```php
|
||||
// ✅ DO: explode()로 분리 후 뒷부분만 해시
|
||||
[, $token] = explode('|', $bearerToken, 2);
|
||||
$hashedToken = hash('sha256', $token);
|
||||
|
||||
// ❌ DON'T: 전체 문자열을 해시
|
||||
$hashedToken = hash('sha256', $bearerToken); // 잘못된 해시값
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 세션 존재 확인
|
||||
|
||||
세션 무효화 전 반드시 세션 존재 여부를 확인해야 합니다:
|
||||
|
||||
```php
|
||||
if (request()->hasSession() && request()->session()->isStarted() && Auth::guard('web')->check()) {
|
||||
// 세션 무효화 로직
|
||||
}
|
||||
```
|
||||
|
||||
**체크 항목**:
|
||||
| 메서드 | 설명 |
|
||||
|--------|------|
|
||||
| `hasSession()` | 세션이 바인딩되어 있는지 확인 |
|
||||
| `isStarted()` | 세션이 실제로 시작되었는지 확인 |
|
||||
| `Auth::guard('web')->check()` | 세션에 인증된 사용자가 있는지 확인 |
|
||||
|
||||
---
|
||||
|
||||
## 세션 무효화 3단계
|
||||
|
||||
```php
|
||||
Auth::guard('web')->logout(); // 1. 세션에서 인증 정보 제거
|
||||
request()->session()->invalidate(); // 2. 세션 ID 무효화 및 새 세션 생성
|
||||
request()->session()->regenerateToken(); // 3. CSRF 토큰 재생성
|
||||
```
|
||||
|
||||
**각 단계 설명**:
|
||||
|
||||
| 단계 | 메서드 | 역할 |
|
||||
|------|--------|------|
|
||||
| 1 | `logout()` | 세션에서 사용자 인증 정보 제거 |
|
||||
| 2 | `invalidate()` | 세션 ID를 무효화하고 새 세션 ID 생성 |
|
||||
| 3 | `regenerateToken()` | CSRF 토큰을 재생성 |
|
||||
|
||||
**regenerateToken()을 하는 이유**:
|
||||
- 로그아웃 후에도 사용자가 같은 브라우저를 계속 사용할 수 있음
|
||||
- 이전 CSRF 토큰을 무효화하고 새로운 CSRF 토큰 발급
|
||||
- 로그아웃 이후의 공개 페이지 요청(로그인 폼 등)을 위한 새로운 보안 토큰 제공
|
||||
|
||||
---
|
||||
|
||||
## 완전한 로그아웃 구현 예시
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class AuthService
|
||||
{
|
||||
/**
|
||||
* 사용자를 로그아웃시키고 현재 디바이스의 인증 토큰만 삭제합니다.
|
||||
*/
|
||||
public function logout(User $user): void
|
||||
{
|
||||
// Hook 발생 (로그아웃 시작)
|
||||
HookManager::doAction('core.auth.before_logout', $user);
|
||||
|
||||
// 토큰 삭제 처리 (토큰 전용 인증이므로 항상 PersonalAccessToken)
|
||||
$token = $user->currentAccessToken();
|
||||
|
||||
if ($token instanceof \Laravel\Sanctum\PersonalAccessToken) {
|
||||
$token->delete();
|
||||
}
|
||||
|
||||
// 세션 무효화 (StartApiSession 미들웨어가 세션을 시작한 경우)
|
||||
if (request()->hasSession() && request()->session()->isStarted() && Auth::guard('web')->check()) {
|
||||
Auth::guard('web')->logout();
|
||||
request()->session()->invalidate();
|
||||
request()->session()->regenerateToken();
|
||||
}
|
||||
|
||||
// Hook 발생 (로그아웃 완료)
|
||||
HookManager::doAction('core.auth.logout', $user);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 안티 패턴
|
||||
|
||||
```php
|
||||
// ❌ DON'T: EnsureFrontendRequestsAreStateful 사용 (제거됨)
|
||||
$middleware->api(prepend: [
|
||||
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
]);
|
||||
|
||||
// ❌ DON'T: 세션 존재 확인 없이 무효화 (에러 발생 가능)
|
||||
Auth::guard('web')->logout(); // 세션이 없으면 에러
|
||||
|
||||
// ❌ DON'T: 토큰 삭제 없이 세션만 무효화
|
||||
request()->session()->invalidate(); // 토큰이 살아있으면 재인증 가능
|
||||
|
||||
// ❌ DON'T: 전체 plainTextToken 해시 (DB 값과 불일치)
|
||||
$hashedToken = hash('sha256', $bearerToken); // 잘못됨
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 참고 자료
|
||||
|
||||
- **구현 파일**: [app/Services/AuthService.php](../../../app/Services/AuthService.php)
|
||||
- **테스트 파일**: [tests/Feature/Api/Admin/AdminAuthTest.php](../../../tests/Feature/Api/Admin/AdminAuthTest.php)
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [index.md](index.md) - 백엔드 가이드 인덱스
|
||||
- [middleware.md](middleware.md) - 미들웨어 등록 규칙 (OptionalSanctumMiddleware 포함)
|
||||
@@ -0,0 +1,478 @@
|
||||
# Broadcasting (실시간 이벤트)
|
||||
|
||||
> **중요도**: 중요
|
||||
> **관련 문서**: [service-repository.md](service-repository.md) | [authentication.md](authentication.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. Laravel Reverb 사용 (WebSocket)
|
||||
2. 이벤트: ShouldBroadcast 인터페이스 구현
|
||||
3. 채널: public, private, presence
|
||||
4. 훅 연동: HookManager에서 broadcast() 호출
|
||||
5. 클라이언트: Laravel Echo + Pusher-js
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [개요](#개요)
|
||||
2. [Laravel Reverb 설정](#laravel-reverb-설정)
|
||||
3. [브로드캐스트 이벤트 생성](#브로드캐스트-이벤트-생성)
|
||||
4. [채널 인증](#채널-인증)
|
||||
5. [API 인증 엔드포인트](#api-인증-엔드포인트)
|
||||
6. [훅을 통한 이벤트 발생](#훅을-통한-이벤트-발생)
|
||||
7. [스케줄러를 통한 주기적 브로드캐스트](#스케줄러를-통한-주기적-브로드캐스트)
|
||||
8. [개발 환경 설정](#개발-환경-설정)
|
||||
9. [프로덕션 환경 설정](#프로덕션-환경-설정)
|
||||
|
||||
---
|
||||
|
||||
## 개요
|
||||
|
||||
G7은 **Laravel Reverb**를 사용하여 실시간 WebSocket 통신을 지원합니다.
|
||||
|
||||
**주요 사용 사례**:
|
||||
- 대시보드 실시간 통계 업데이트
|
||||
- 알림 실시간 전송
|
||||
- 채팅 기능
|
||||
- 실시간 협업 기능
|
||||
|
||||
**아키텍처**:
|
||||
```
|
||||
클라이언트 (Echo/Pusher-js)
|
||||
↕ WebSocket
|
||||
Laravel Reverb 서버
|
||||
↕
|
||||
Laravel 백엔드 (broadcast() 호출)
|
||||
↕
|
||||
Queue Worker (이벤트 처리)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Laravel Reverb 설정
|
||||
|
||||
### 환경변수 (.env)
|
||||
|
||||
```env
|
||||
# Broadcasting 드라이버
|
||||
BROADCAST_CONNECTION=reverb
|
||||
|
||||
# Reverb 서버 설정
|
||||
REVERB_APP_ID=467955
|
||||
REVERB_APP_KEY=zm0vobuy4zpqorc3ro9r
|
||||
REVERB_APP_SECRET=your-secret-key
|
||||
REVERB_HOST=localhost
|
||||
REVERB_PORT=8080
|
||||
REVERB_SCHEME=https
|
||||
|
||||
# 개발 환경에서 자체 서명 인증서 사용 시
|
||||
REVERB_VERIFY_SSL=false
|
||||
|
||||
# 클라이언트용 설정 (Vite)
|
||||
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
|
||||
VITE_REVERB_HOST="${REVERB_HOST}"
|
||||
VITE_REVERB_PORT="${REVERB_PORT}"
|
||||
VITE_REVERB_SCHEME="${REVERB_SCHEME}"
|
||||
```
|
||||
|
||||
### config/broadcasting.php
|
||||
|
||||
```php
|
||||
'reverb' => [
|
||||
'driver' => 'reverb',
|
||||
'key' => env('REVERB_APP_KEY'),
|
||||
'secret' => env('REVERB_APP_SECRET'),
|
||||
'app_id' => env('REVERB_APP_ID'),
|
||||
'options' => [
|
||||
'host' => env('REVERB_HOST'),
|
||||
'port' => env('REVERB_PORT', 443),
|
||||
'scheme' => env('REVERB_SCHEME', 'https'),
|
||||
'useTLS' => env('REVERB_SCHEME', 'https') === 'https',
|
||||
],
|
||||
'client_options' => [
|
||||
// 개발 환경에서 자체 서명 인증서 사용 시 SSL 검증 비활성화
|
||||
'verify' => env('REVERB_VERIFY_SSL', true),
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
> **주의**: 프로덕션 환경에서는 `REVERB_VERIFY_SSL=true`로 설정해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
## 브로드캐스트 이벤트 생성
|
||||
|
||||
### 기본 구조
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Events\Dashboard;
|
||||
|
||||
use Illuminate\Broadcasting\Channel;
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Broadcasting\PrivateChannel;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 대시보드 업데이트 브로드캐스트 이벤트
|
||||
*/
|
||||
class DashboardUpdated implements ShouldBroadcast
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
/**
|
||||
* 이벤트 인스턴스를 생성합니다.
|
||||
*
|
||||
* @param string $type 업데이트 타입 ('stats', 'resources', 'activities')
|
||||
* @param array $data 업데이트된 데이터
|
||||
*/
|
||||
public function __construct(
|
||||
public string $type,
|
||||
public array $data
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 브로드캐스트할 채널을 반환합니다.
|
||||
*
|
||||
* @return array<int, \Illuminate\Broadcasting\Channel>
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PrivateChannel('admin.dashboard')];
|
||||
}
|
||||
|
||||
/**
|
||||
* 브로드캐스트 이벤트명을 반환합니다.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function broadcastAs(): string
|
||||
{
|
||||
return "dashboard.{$this->type}.updated";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 채널 타입
|
||||
|
||||
| 타입 | 클래스 | 용도 | 인증 필요 |
|
||||
|------|--------|------|----------|
|
||||
| Public | `Channel` | 모든 사용자 접근 가능 | ❌ |
|
||||
| Private | `PrivateChannel` | 인증된 사용자만 접근 | ✅ |
|
||||
| Presence | `PresenceChannel` | 인증 + 접속자 목록 공유 | ✅ |
|
||||
|
||||
### 이벤트 발생
|
||||
|
||||
```php
|
||||
// 방법 1: broadcast() 헬퍼 (권장)
|
||||
broadcast(new DashboardUpdated('stats', $statsData));
|
||||
|
||||
// 방법 2: event() 헬퍼
|
||||
event(new DashboardUpdated('resources', $resourceData));
|
||||
|
||||
// 방법 3: 즉시 전송 (큐 미사용)
|
||||
broadcast(new DashboardUpdated('alerts', $alertData))->toOthers();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 채널 인증
|
||||
|
||||
### routes/channels.php
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Broadcast;
|
||||
|
||||
// 사용자별 Private 채널
|
||||
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
|
||||
return (int) $user->id === (int) $id;
|
||||
});
|
||||
|
||||
// 관리자 대시보드 채널 - 권한 체크
|
||||
Broadcast::channel('admin.dashboard', function ($user) {
|
||||
return $user->hasPermission('core.dashboard.read');
|
||||
});
|
||||
|
||||
// 특정 리소스 채널
|
||||
Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
|
||||
return $user->hasPermission('ecommerce.orders.read');
|
||||
});
|
||||
```
|
||||
|
||||
### 인증 콜백 규칙
|
||||
|
||||
```php
|
||||
// ✅ DO: boolean 반환 (Private 채널)
|
||||
Broadcast::channel('admin.dashboard', function ($user) {
|
||||
return $user->hasPermission('core.dashboard.read');
|
||||
});
|
||||
|
||||
// ✅ DO: 배열 반환 (Presence 채널 - 사용자 정보 공유)
|
||||
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
|
||||
if ($user->canJoinRoom($roomId)) {
|
||||
return ['id' => $user->id, 'name' => $user->name];
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
// ❌ DON'T: 예외 던지기
|
||||
Broadcast::channel('admin.dashboard', function ($user) {
|
||||
throw new \Exception('Unauthorized'); // 금지
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 인증 엔드포인트
|
||||
|
||||
G7은 SPA 환경에서 **Sanctum 토큰 기반 인증**을 사용합니다. 기본 `/broadcasting/auth` 엔드포인트는 세션 기반이므로, API용 별도 엔드포인트를 사용합니다.
|
||||
|
||||
### routes/api.php
|
||||
|
||||
```php
|
||||
// 브로드캐스팅 인증 (Sanctum 토큰 사용)
|
||||
Route::middleware(['auth:sanctum'])->post('broadcasting/auth', function (\Illuminate\Http\Request $request) {
|
||||
return \Illuminate\Support\Facades\Broadcast::auth($request);
|
||||
})->name('api.broadcasting.auth');
|
||||
```
|
||||
|
||||
### 클라이언트 설정 (WebSocketManager)
|
||||
|
||||
```typescript
|
||||
const pusherOptions = {
|
||||
// ... 기타 옵션
|
||||
authEndpoint: '/api/broadcasting/auth',
|
||||
auth: {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${authToken}`,
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 훅을 통한 이벤트 발생
|
||||
|
||||
Service 계층에서 데이터 변경 시 훅 리스너를 통해 브로드캐스트 이벤트를 발생시킵니다.
|
||||
|
||||
### config/hooks.php
|
||||
|
||||
```php
|
||||
return [
|
||||
'listeners' => [
|
||||
// 대시보드 통계 업데이트 시 브로드캐스트
|
||||
'core.dashboard.stats_updated' => [
|
||||
\App\Listeners\BroadcastDashboardStats::class,
|
||||
],
|
||||
|
||||
// 사용자 생성 시 대시보드 통계 업데이트
|
||||
'core.user.after_create' => [
|
||||
\App\Listeners\UpdateDashboardStatsOnUserChange::class,
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
### 리스너 구현
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Events\Dashboard\DashboardUpdated;
|
||||
use App\Services\DashboardService;
|
||||
|
||||
class BroadcastDashboardStats
|
||||
{
|
||||
public function __construct(
|
||||
private DashboardService $dashboardService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 대시보드 통계 브로드캐스트
|
||||
*
|
||||
* @param array $data 훅 데이터
|
||||
* @return void
|
||||
*/
|
||||
public function handle(array $data): void
|
||||
{
|
||||
$stats = $this->dashboardService->getStats();
|
||||
broadcast(new DashboardUpdated('stats', $stats));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 스케줄러를 통한 주기적 브로드캐스트
|
||||
|
||||
시스템 리소스 등 주기적으로 업데이트가 필요한 데이터는 스케줄러를 사용합니다.
|
||||
|
||||
### Artisan 커맨드
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Events\Dashboard\DashboardUpdated;
|
||||
use App\Services\DashboardService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class BroadcastDashboardResources extends Command
|
||||
{
|
||||
protected $signature = 'dashboard:broadcast-resources';
|
||||
protected $description = '시스템 리소스 정보를 WebSocket으로 브로드캐스트합니다.';
|
||||
|
||||
public function handle(DashboardService $dashboardService): int
|
||||
{
|
||||
$resources = $dashboardService->getSystemResources();
|
||||
broadcast(new DashboardUpdated('resources', $resources));
|
||||
|
||||
$this->info('시스템 리소스 정보가 브로드캐스트되었습니다.');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### routes/console.php (스케줄러 등록)
|
||||
|
||||
```php
|
||||
use Illuminate\Support\Facades\Schedule;
|
||||
|
||||
// 30초마다 시스템 리소스 브로드캐스트
|
||||
Schedule::command('dashboard:broadcast-resources')->everyThirtySeconds();
|
||||
```
|
||||
|
||||
### 실행 방법
|
||||
|
||||
```bash
|
||||
# 스케줄러 실행 (개발 환경)
|
||||
php artisan schedule:work
|
||||
|
||||
# 큐 워커 실행 (브로드캐스트 이벤트 처리)
|
||||
php artisan queue:work
|
||||
|
||||
# Reverb 서버 실행
|
||||
php artisan reverb:start --debug
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 개발 환경 설정
|
||||
|
||||
### 필요한 프로세스
|
||||
|
||||
개발 환경에서 WebSocket을 테스트하려면 다음 프로세스가 모두 실행 중이어야 합니다:
|
||||
|
||||
```bash
|
||||
# 터미널 1: Laravel 개발 서버
|
||||
php artisan serve
|
||||
|
||||
# 터미널 2: Reverb WebSocket 서버
|
||||
php artisan reverb:start --debug
|
||||
|
||||
# 터미널 3: 큐 워커 (브로드캐스트 이벤트 처리)
|
||||
php artisan queue:work
|
||||
|
||||
# 터미널 4: 스케줄러 (주기적 브로드캐스트 사용 시)
|
||||
php artisan schedule:work
|
||||
```
|
||||
|
||||
### SSL 인증서 문제 해결
|
||||
|
||||
개발 환경에서 자체 서명 인증서 사용 시 다음 설정이 필요합니다:
|
||||
|
||||
```env
|
||||
# .env
|
||||
REVERB_VERIFY_SSL=false
|
||||
```
|
||||
|
||||
이 설정은 Laravel이 Reverb 서버로 이벤트를 전송할 때 SSL 인증서 검증을 비활성화합니다.
|
||||
|
||||
---
|
||||
|
||||
## 프로덕션 환경 설정
|
||||
|
||||
### 권장 설정
|
||||
|
||||
```env
|
||||
# .env (프로덕션)
|
||||
REVERB_VERIFY_SSL=true
|
||||
REVERB_SCHEME=https
|
||||
REVERB_PORT=443
|
||||
```
|
||||
|
||||
### Supervisor 설정 예시
|
||||
|
||||
```ini
|
||||
[program:reverb]
|
||||
command=php /var/www/g7/artisan reverb:start
|
||||
directory=/var/www/g7
|
||||
user=www-data
|
||||
autostart=true
|
||||
autorestart=true
|
||||
redirect_stderr=true
|
||||
stdout_logfile=/var/log/reverb.log
|
||||
|
||||
[program:queue-worker]
|
||||
command=php /var/www/g7/artisan queue:work --sleep=3 --tries=3
|
||||
directory=/var/www/g7
|
||||
user=www-data
|
||||
autostart=true
|
||||
autorestart=true
|
||||
redirect_stderr=true
|
||||
stdout_logfile=/var/log/queue-worker.log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 디버깅
|
||||
|
||||
### 이벤트 전송 확인
|
||||
|
||||
```bash
|
||||
# 수동으로 이벤트 발생
|
||||
php artisan dashboard:broadcast-resources
|
||||
|
||||
# 큐 작업 확인
|
||||
php artisan queue:work --once
|
||||
```
|
||||
|
||||
### 로그 확인
|
||||
|
||||
```bash
|
||||
# Laravel 로그
|
||||
tail -f storage/logs/laravel.log
|
||||
|
||||
# Reverb 서버 로그 (--debug 옵션 사용 시)
|
||||
php artisan reverb:start --debug
|
||||
```
|
||||
|
||||
### 클라이언트 디버깅
|
||||
|
||||
브라우저 개발자 도구에서:
|
||||
1. **Network** 탭 → **WS** 필터 → WebSocket 연결 확인
|
||||
2. **Messages** 탭에서 송수신 메시지 확인
|
||||
3. **Console** 탭에서 `[WebSocketManager]` 로그 확인
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [Service-Repository 패턴](service-repository.md) - 훅 실행 위치
|
||||
- [인증](authentication.md) - Sanctum 토큰 인증
|
||||
- [프론트엔드 WebSocket](../frontend/data-sources-advanced.md) - 클라이언트 WebSocket 구독
|
||||
@@ -0,0 +1,319 @@
|
||||
# 컨트롤러 계층 구조
|
||||
|
||||
> **관련 문서**: [index.md](index.md) | [service-repository.md](service-repository.md) | [validation.md](validation.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. AdminBaseController / AuthBaseController / PublicBaseController 중 상속
|
||||
2. Service 주입 필수 (Repository 직접 주입 금지)
|
||||
3. FormRequest로 검증 (컨트롤러에 검증 로직 금지)
|
||||
4. ResponseHelper 메서드 사용 (success, error, successWithResource)
|
||||
5. 네이밍: [Entity][Action]Controller (예: UserListController)
|
||||
6. array_filter 시 null만 제거 (빈 문자열은 사용자 의도로 보존)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [Base 컨트롤러 계층](#base-컨트롤러-계층)
|
||||
2. [각 컨트롤러 역할](#각-컨트롤러-역할)
|
||||
3. [컨트롤러 네이밍 규칙](#컨트롤러-네이밍-규칙)
|
||||
4. [응답 메서드 사용](#응답-메서드-사용)
|
||||
5. [Controller 규칙](#controller-규칙)
|
||||
6. [패턴 예시](#패턴-예시)
|
||||
7. [데이터 필터링 패턴 (array_filter)](#데이터-필터링-패턴-array_filter)
|
||||
8. [체크리스트](#체크리스트)
|
||||
|
||||
---
|
||||
|
||||
## Base 컨트롤러 계층
|
||||
|
||||
G7은 역할 기반의 컨트롤러 계층 구조를 사용합니다.
|
||||
|
||||
```text
|
||||
BaseApiController (최상위)
|
||||
├── AdminBaseController (관리자 전용)
|
||||
├── AuthBaseController (인증된 사용자)
|
||||
└── PublicBaseController (공개 API)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 각 컨트롤러 역할
|
||||
|
||||
### BaseApiController
|
||||
|
||||
**경로**: `app/Http/Controllers/Api/Base/BaseApiController.php`
|
||||
|
||||
- 모든 API 컨트롤러의 최상위 부모 클래스
|
||||
- 공통 응답 메서드 제공: `success()`, `error()`, `successWithResource()`, `notFound()`, `unauthorized()`, `forbidden()`, `validationError()`
|
||||
- 인증 사용자 조회: `getCurrentUser()`
|
||||
|
||||
### AdminBaseController
|
||||
|
||||
**경로**: `app/Http/Controllers/Api/Base/AdminBaseController.php`
|
||||
|
||||
- BaseApiController 상속
|
||||
- 관리자 전용 기능
|
||||
- 미들웨어: `['auth:sanctum', 'admin']`
|
||||
- 관리자 활동 로깅: `logAdminActivity()`
|
||||
|
||||
### AuthBaseController
|
||||
|
||||
**경로**: `app/Http/Controllers/Api/Base/AuthBaseController.php`
|
||||
|
||||
- BaseApiController 상속
|
||||
- 인증된 사용자 전용 기능
|
||||
- 미들웨어: `['auth:sanctum']`
|
||||
- 리소스 소유권 확인: `isOwner()`, `canAccessResource()`, `checkOwnership()`
|
||||
- 사용자 활동 로깅: `logUserActivity()`
|
||||
|
||||
### PublicBaseController
|
||||
|
||||
**경로**: `app/Http/Controllers/Api/Base/PublicBaseController.php`
|
||||
|
||||
- BaseApiController 상속
|
||||
- 인증 불필요한 공개 API
|
||||
- 미들웨어: `['throttle:60,1']` (속도 제한)
|
||||
- 캐싱: `cached()`
|
||||
- API 사용량 추적: `logApiUsage()`, `getClientInfo()`
|
||||
|
||||
---
|
||||
|
||||
## 컨트롤러 네이밍 규칙
|
||||
|
||||
### 코어
|
||||
|
||||
| 역할 | 경로 |
|
||||
|------|------|
|
||||
| 관리자 | `app/Http/Controllers/Api/Admin/[기능명]Controller.php` |
|
||||
| 인증 사용자 | `app/Http/Controllers/Api/Auth/[기능명]Controller.php` |
|
||||
| 공개 API | `app/Http/Controllers/Api/Public/[기능명]Controller.php` |
|
||||
|
||||
### 모듈
|
||||
|
||||
| 역할 | 경로 |
|
||||
|------|------|
|
||||
| 관리자 | `modules/[vendor-module]/src/Controllers/Api/Admin/[기능명]Controller.php` |
|
||||
| 인증 사용자 | `modules/[vendor-module]/src/Controllers/Api/Auth/[기능명]Controller.php` |
|
||||
| 공개 API | `modules/[vendor-module]/src/Controllers/Api/[기능명]Controller.php` |
|
||||
|
||||
---
|
||||
|
||||
## 응답 메서드 사용
|
||||
|
||||
모든 컨트롤러는 Base 클래스의 공통 메서드를 사용합니다:
|
||||
|
||||
```php
|
||||
// ✅ DO: 공통 메서드 사용
|
||||
return $this->success('messages.created', $data, 201);
|
||||
return $this->error('messages.failed', 400);
|
||||
return $this->successWithResource('messages.success', new UserResource($user));
|
||||
return $this->notFound('messages.not_found');
|
||||
return $this->unauthorized('messages.unauthorized');
|
||||
return $this->forbidden('messages.forbidden');
|
||||
return $this->validationError($errors, 'messages.validation_failed');
|
||||
|
||||
// ❌ DON'T: 역할별 래퍼 메서드 사용 (Deprecated)
|
||||
// adminSuccess(), userSuccess(), publicSuccess() 등은 사용하지 않음
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Controller 규칙
|
||||
|
||||
### 원칙
|
||||
|
||||
- Service 클래스를 생성자 주입으로 받음
|
||||
- 비즈니스 로직은 Service에 위임
|
||||
- ResponseHelper 사용
|
||||
- 인라인 검증 금지 (FormRequest 사용)
|
||||
|
||||
> **참고**: FormRequest 상세 규칙은 [validation.md](validation.md) 참조
|
||||
|
||||
---
|
||||
|
||||
## 패턴 예시
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Controllers\Api\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
use Modules\Sirsoft\Ecommerce\Requests\StoreProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Requests\UpdateProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Resources\ProductResource;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ProductController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private ProductService $productService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 상품 목록 조회
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$products = $this->productService->getAllProducts();
|
||||
|
||||
return ResponseHelper::success(
|
||||
ProductResource::collection($products),
|
||||
'상품 목록을 조회했습니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 생성
|
||||
*/
|
||||
public function store(StoreProductRequest $request): JsonResponse
|
||||
{
|
||||
$product = $this->productService->createProduct($request->validated());
|
||||
|
||||
return ResponseHelper::success(
|
||||
new ProductResource($product),
|
||||
'상품이 생성되었습니다.',
|
||||
201
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 수정
|
||||
*/
|
||||
public function update(UpdateProductRequest $request, int $id): JsonResponse
|
||||
{
|
||||
$product = $this->productService->updateProduct($id, $request->validated());
|
||||
|
||||
return ResponseHelper::success(
|
||||
new ProductResource($product),
|
||||
'상품이 수정되었습니다.'
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 데이터 필터링 패턴 (array_filter)
|
||||
|
||||
컨트롤러에서 요청 데이터를 Service에 전달하기 전에 `array_filter`로 불필요한 값을 제거하는 경우, **빈 문자열(`''`)과 `null`의 의미 차이**에 주의해야 합니다.
|
||||
|
||||
### null vs 빈 문자열의 의미
|
||||
|
||||
| 값 | 의미 | 예시 |
|
||||
|------|------|------|
|
||||
| `null` | 필드가 전송되지 않음 (미포함) | JSON body에 키 자체가 없음 |
|
||||
| `''` (빈 문자열) | 사용자가 의도적으로 값을 비움 | 기존 값을 지우려는 의도 |
|
||||
|
||||
### 잘못된 예시 (빈 문자열 제거)
|
||||
|
||||
```php
|
||||
// ❌ DON'T: 빈 문자열도 제거 → 사용자의 "값 비우기" 의도 무시
|
||||
$data = collect($validated)
|
||||
->filter(fn ($v) => $v !== null && $v !== '')
|
||||
->toArray();
|
||||
```
|
||||
|
||||
### 올바른 예시 (null만 제거)
|
||||
|
||||
```php
|
||||
// ✅ DO: null만 제거 → 빈 문자열은 사용자 의도로 보존
|
||||
$data = collect($validated)
|
||||
->filter(fn ($v) => $v !== null)
|
||||
->toArray();
|
||||
```
|
||||
|
||||
### 적용 시점
|
||||
|
||||
| 상황 | 권장 패턴 |
|
||||
|------|----------|
|
||||
| 설정 Override (기본값 위에 덮어쓰기) | `null`만 제거 (빈 문자열 = 기본값으로 초기화) |
|
||||
| 일반 CRUD 저장 | `validated()` 그대로 사용 (필터링 불필요) |
|
||||
| 선택적 필드 업데이트 (PATCH) | `null`만 제거 또는 `filled()` 활용 |
|
||||
|
||||
---
|
||||
|
||||
## 표준 예외 처리 패턴
|
||||
|
||||
컨트롤러에서 Service 호출 시 다음 표준 예외 처리 패턴을 사용합니다:
|
||||
|
||||
```php
|
||||
public function store(StoreProductRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$product = $this->productService->createProduct($request->validated());
|
||||
|
||||
return $this->success('product.create_success', new ProductResource($product), 201);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->validationError($e->errors(), 'product.create_failed');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('product.create_failed', 500);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 예외 유형별 처리
|
||||
|
||||
| 예외 유형 | 응답 메서드 | 상태 코드 | 용도 |
|
||||
| ---------- | ----------- | ---------- | ------ |
|
||||
| `ValidationException` | `validationError()` | 422 | Service에서 발생한 검증 예외 |
|
||||
| `AccessDeniedHttpException` | `error()` | 403 | 스코프 접근 거부 |
|
||||
| 커스텀 비즈니스 예외 | `error()` | 400~409 | 비즈니스 규칙 위반 |
|
||||
| `\Exception` (범용) | `error()` | 500 | 예상치 못한 오류 |
|
||||
|
||||
### 스코프 접근 거부 처리 패턴
|
||||
|
||||
```php
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$item = $this->service->getItem($id);
|
||||
return $this->success('item.fetch_success', new ItemResource($item));
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('item.fetch_failed', 500);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 주의사항
|
||||
|
||||
- `ValidationException`은 `\Exception`보다 **먼저** catch해야 함 (하위 클래스 우선)
|
||||
- 에러 메시지는 반드시 `__()` 다국어 키 사용 (하드코딩 금지)
|
||||
- `$e->getMessage()`는 **로깅 목적**으로만 사용 (사용자에게 직접 노출 금지)
|
||||
|
||||
---
|
||||
|
||||
## 체크리스트
|
||||
|
||||
### 컨트롤러 개발 체크리스트
|
||||
|
||||
- [ ] 적절한 Base 컨트롤러를 상속했는가?
|
||||
- 관리자 기능 → `AdminBaseController`
|
||||
- 인증 사용자 기능 → `AuthBaseController`
|
||||
- 공개 API → `PublicBaseController`
|
||||
- [ ] Service 클래스를 생성자 주입으로 받았는가?
|
||||
- [ ] 비즈니스 로직을 Service에 위임했는가?
|
||||
- [ ] ResponseHelper를 사용해 응답했는가?
|
||||
- [ ] FormRequest를 사용해 검증했는가? (인라인 검증 금지)
|
||||
- [ ] 네이밍 규칙을 준수했는가?
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [index.md](index.md) - 백엔드 가이드 인덱스
|
||||
- [service-repository.md](service-repository.md) - Service-Repository 패턴
|
||||
- [validation.md](validation.md) - 검증 로직 구현 원칙
|
||||
- [response-helper.md](response-helper.md) - API 응답 규칙
|
||||
@@ -0,0 +1,201 @@
|
||||
# 코어 설정 (config/core.php)
|
||||
|
||||
> **목적**: 코어 시스템의 권한, 역할, 메뉴, 메일 템플릿 정의 파일 구조 설명
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. config/core.php = 코어 권한/역할/메뉴/메일템플릿의 SSoT (Single Source of Truth)
|
||||
2. 구조: module(1레벨) → categories(2레벨) → permissions(3레벨) 3단계
|
||||
3. 설치(Seeder) + 업데이트(CoreUpdateService) 모두 이 파일에서 읽음
|
||||
4. 모듈/플러그인은 config/core.php 대신 자체 config.php에 동일 구조로 정의
|
||||
5. 수정 시 Seeder/Sync 로직이 자동 반영 (수동 마이그레이션 불필요)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
- [파일 구조 개요](#파일-구조-개요)
|
||||
- [permissions — 권한 정의](#permissions--권한-정의)
|
||||
- [roles — 역할 정의](#roles--역할-정의)
|
||||
- [menus — 메뉴 정의](#menus--메뉴-정의)
|
||||
- [mail_templates — 메일 템플릿 정의](#mail_templates--메일-템플릿-정의)
|
||||
- [사용처](#사용처)
|
||||
- [관련 문서](#관련-문서)
|
||||
|
||||
---
|
||||
|
||||
## 파일 구조 개요
|
||||
|
||||
`config/core.php`는 4개 최상위 키로 구성됩니다:
|
||||
|
||||
```php
|
||||
return [
|
||||
'permissions' => [...], // 코어 권한 정의
|
||||
'roles' => [...], // 코어 역할 정의
|
||||
'menus' => [...], // 코어 메뉴 정의
|
||||
'mail_templates' => [...], // 코어 메일 템플릿 정의
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## permissions — 권한 정의
|
||||
|
||||
3레벨 계층 구조:
|
||||
|
||||
```text
|
||||
permissions
|
||||
├── module (1레벨) → identifier, name, description, order
|
||||
└── categories (2레벨 배열)
|
||||
├── category 항목 → identifier, name, description, category, order
|
||||
└── permissions (3레벨) → identifier, name, description, order, resource_route_key?, owner_key?
|
||||
```
|
||||
|
||||
### module (1레벨)
|
||||
|
||||
```php
|
||||
'module' => [
|
||||
'identifier' => 'core',
|
||||
'name' => ['ko' => '코어', 'en' => 'Core'],
|
||||
'description' => ['ko' => '코어 시스템 권한', 'en' => 'Core system permissions'],
|
||||
'order' => 1,
|
||||
],
|
||||
```
|
||||
|
||||
### categories (2레벨) + permissions (3레벨)
|
||||
|
||||
```php
|
||||
'categories' => [
|
||||
[
|
||||
'identifier' => 'core.users',
|
||||
'name' => ['ko' => '사용자 관리', 'en' => 'User Management'],
|
||||
'description' => [...],
|
||||
'category' => 'users', // 카테고리 슬러그
|
||||
'order' => 1,
|
||||
'permissions' => [
|
||||
[
|
||||
'identifier' => 'core.users.read',
|
||||
'name' => ['ko' => '사용자 조회', 'en' => 'View Users'],
|
||||
'description' => [...],
|
||||
'order' => 1,
|
||||
'resource_route_key' => 'user', // scope 체크 시 라우트 모델 키 (선택)
|
||||
'owner_key' => 'id', // scope 체크 시 소유자 필드 (선택)
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
### 권한 필드 설명
|
||||
|
||||
| 필드 | 필수 | 설명 |
|
||||
| ---------- | ---------- | ---------- |
|
||||
| `identifier` | ✅ | 권한 식별자 (예: `core.users.read`) |
|
||||
| `name` | ✅ | 다국어 이름 배열 `['ko' => ..., 'en' => ...]` |
|
||||
| `description` | ✅ | 다국어 설명 배열 |
|
||||
| `order` | ✅ | 정렬 순서 |
|
||||
| `resource_route_key` | ❌ | scope 기반 접근 체크 시 라우트 모델 바인딩 키 |
|
||||
| `owner_key` | ❌ | scope 기반 접근 체크 시 소유자 판단 필드 |
|
||||
|
||||
---
|
||||
|
||||
## roles — 역할 정의
|
||||
|
||||
```php
|
||||
'roles' => [
|
||||
[
|
||||
'identifier' => 'admin',
|
||||
'name' => ['ko' => '관리자', 'en' => 'Administrator'],
|
||||
'description' => [...],
|
||||
'attributes' => ['is_active' => true],
|
||||
'permissions' => 'all_leaf', // 특수 값: 모든 리프 권한 할당
|
||||
],
|
||||
[
|
||||
'identifier' => 'manager',
|
||||
'name' => ['ko' => '매니저', 'en' => 'Manager'],
|
||||
'permissions' => ['core.users.read', 'core.users.create', ...],
|
||||
'permission_scopes' => [
|
||||
'core.users.read' => 'self', // 본인 리소스만
|
||||
'core.users.update' => 'self',
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
### 역할 필드 설명
|
||||
|
||||
| 필드 | 필수 | 설명 |
|
||||
| ---------- | ---------- | ---------- |
|
||||
| `identifier` | ✅ | 역할 식별자 (예: `admin`, `manager`) |
|
||||
| `name` | ✅ | 다국어 이름 배열 |
|
||||
| `description` | ✅ | 다국어 설명 배열 |
|
||||
| `attributes` | ❌ | 추가 속성 (`is_active` 등) |
|
||||
| `permissions` | ✅ | 권한 배열 또는 `'all_leaf'` (모든 리프 권한) |
|
||||
| `permission_scopes` | ❌ | 권한별 scope_type 매핑 (`'self'` / `'role'` / 미지정=전체) |
|
||||
|
||||
---
|
||||
|
||||
## menus — 메뉴 정의
|
||||
|
||||
```php
|
||||
'menus' => [
|
||||
[
|
||||
'slug' => 'admin-dashboard',
|
||||
'name' => ['ko' => '대시보드', 'en' => 'Dashboard'],
|
||||
'url' => '/admin/dashboard',
|
||||
'icon' => 'fas fa-tachometer-alt',
|
||||
'parent_id' => null,
|
||||
'order' => 1,
|
||||
'is_active' => true,
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## mail_templates — 메일 템플릿 정의
|
||||
|
||||
```php
|
||||
'mail_templates' => [
|
||||
[
|
||||
'type' => 'welcome',
|
||||
'subject' => ['ko' => '[{app_name}] 환영합니다', 'en' => '...'],
|
||||
'body' => ['ko' => '<h1>{name}님...</h1>', 'en' => '...'],
|
||||
'variables' => [
|
||||
['key' => 'name', 'description' => '수신자 이름'],
|
||||
['key' => 'app_name', 'description' => '사이트명'],
|
||||
],
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
### variables 배열
|
||||
|
||||
메일 템플릿에서 사용 가능한 치환 변수를 정의합니다. `{key}` 형태로 subject/body에서 사용됩니다.
|
||||
|
||||
---
|
||||
|
||||
## 사용처
|
||||
|
||||
| 사용처 | 시점 | 설명 |
|
||||
| ---------- | ---------- | ---------- |
|
||||
| `RolePermissionSeeder` | 초기 설치 | permissions, roles 데이터 시딩 |
|
||||
| `CoreAdminMenuSeeder` | 초기 설치 | menus 데이터 시딩 |
|
||||
| `MailTemplateSeeder` | 초기 설치 | mail_templates 데이터 시딩 |
|
||||
| `CoreUpdateService::syncCoreRolesAndPermissions()` | 코어 업데이트 | 권한/역할 동기화 |
|
||||
| `CoreUpdateService::syncCoreMenus()` | 코어 업데이트 | 메뉴 동기화 |
|
||||
| `CoreUpdateService::syncCoreMailTemplates()` | 코어 업데이트 | 메일 템플릿 동기화 |
|
||||
|
||||
**핵심 원칙**: 새 권한/역할/메뉴/메일템플릿 추가 시 이 파일에 추가하면 설치/업데이트 모두 자동 반영됩니다.
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [permissions.md](../extension/permissions.md) - 권한 시스템 상세
|
||||
- [module-basics.md](../extension/module-basics.md) - 모듈별 config.php 구조
|
||||
- [service-provider.md](service-provider.md) - 서비스 프로바이더에서 config 로드
|
||||
@@ -0,0 +1,740 @@
|
||||
# 코어 업데이트 시스템 (Core Update System)
|
||||
|
||||
> 코어 버전 업데이트의 감지, 다운로드, 적용, 롤백, 업그레이드 스텝 실행을 관리하는 시스템
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 코어 업그레이드 스텝: upgrades/ 디렉토리 (프로젝트 루트), 네임스페이스 App\Upgrades
|
||||
2. 마이그레이션 = 스키마 변경만, 데이터 백필/변환 = 업그레이드 스텝 (역할 분리 필수)
|
||||
3. 업데이트 실행 흐름: 11단계 (감지 → 다운로드 → 백업 → 적용 → 마이그레이션 → 동기화 → 업그레이드 → 마무리)
|
||||
4. 롤백: CoreBackupHelper로 백업 생성, 실패 시 자동 복원
|
||||
5. 부트스트랩 호환성 검증: .env의 APP_VERSION < 확장 g7_version 시 자동 비활성화 (1시간 캐시)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [업데이트 감지](#1-업데이트-감지)
|
||||
2. [업데이트 실행 흐름 (11단계)](#2-업데이트-실행-흐름-11단계)
|
||||
3. [백업 및 롤백](#3-백업-및-롤백)
|
||||
4. [마이그레이션 vs 업그레이드 스텝](#4-마이그레이션-vs-업그레이드-스텝)
|
||||
5. [업그레이드 스텝 작성](#5-업그레이드-스텝-작성)
|
||||
6. [자동 발견 및 실행 규칙](#6-자동-발견-및-실행-규칙)
|
||||
7. [버전 관리](#7-버전-관리)
|
||||
8. [CoreUpdateService 주요 메서드](#8-coreupdateservice-주요-메서드)
|
||||
9. [Artisan 커맨드](#9-artisan-커맨드)
|
||||
10. [API 엔드포인트](#10-api-엔드포인트)
|
||||
11. [설정 (config/app.php)](#11-설정-configappphp)
|
||||
12. [에러 처리 및 로깅](#12-에러-처리-및-로깅)
|
||||
13. [유지보수 모드](#13-유지보수-모드)
|
||||
14. [코어 vs 확장 업데이트 비교](#14-코어-vs-확장-업데이트-비교)
|
||||
|
||||
---
|
||||
|
||||
## 1. 업데이트 감지
|
||||
|
||||
> 파일: `app/Extension/CoreVersionChecker.php`, `app/Services/CoreUpdateService.php`
|
||||
|
||||
### 감지 흐름
|
||||
|
||||
```text
|
||||
1. CoreVersionChecker::getCoreVersion() → config('app.version') 읽기
|
||||
2. CoreUpdateService::checkForUpdates() → GitHub API로 최신 릴리스 조회
|
||||
3. version_compare(current, latest) → 업데이트 가용 여부 판단
|
||||
4. 원격 CHANGELOG 캐시 → storage/app/temp/core_remote_changelog.md
|
||||
```
|
||||
|
||||
### GitHub API 통합
|
||||
|
||||
```text
|
||||
- config('app.update.github_url') 에서 리포지토리 URL 읽기
|
||||
- config('app.update.github_token') 으로 인증 (선택)
|
||||
- GitHub Releases API 호출 → 최신 릴리스 태그에서 버전 추출
|
||||
```
|
||||
|
||||
### 감지 결과
|
||||
|
||||
```php
|
||||
[
|
||||
'update_available' => true,
|
||||
'current_version' => '7.0.0-alpha.14',
|
||||
'latest_version' => '7.0.0-alpha.15',
|
||||
'check_failed' => false, // GitHub API 실패 시 true
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 업데이트 실행 흐름 (11단계)
|
||||
|
||||
> 파일: `app/Console/Commands/Core/CoreUpdateCommand.php`
|
||||
|
||||
```text
|
||||
┌─ Step 1: 업데이트 확인 (GitHub API 또는 --source/--local 모드)
|
||||
├─ Step 2: _pending 경로 검증 (디렉토리 존재/쓰기 권한)
|
||||
├─ Step 3: 유지보수 모드 활성화 (--no-maintenance 시 스킵)
|
||||
├─ Step 4: 다운로드 (GitHub zipball 또는 --source/--local에서 복사)
|
||||
├─ Step 5: 백업 생성 (--no-backup 시 스킵)
|
||||
├─ Step 6: Composer install (_pending에서 실행, 변경 없으면 스킵)
|
||||
├─ Step 7: 파일 적용 (_pending → base_path 선택적 덮어쓰기)
|
||||
├─ Step 8: vendor 복사 (_pending/vendor → base_path/vendor, Step 6 스킵 시 함께 스킵)
|
||||
├─ Step 9: 마이그레이션 + 동기화 (migrate, roles, permissions, menus, mail templates)
|
||||
├─ Step 10: 업그레이드 스텝 실행 (upgrades/Upgrade_X_Y_Z.php)
|
||||
└─ Step 11: 마무리 (.env 버전 갱신, 캐시 클리어, _pending 삭제, 유지보수 해제)
|
||||
```
|
||||
|
||||
### Step 1: 업데이트 확인
|
||||
|
||||
| 모드 | 동작 |
|
||||
|------|------|
|
||||
| 일반 | `checkForUpdates()` → GitHub API 호출 → 사용자 확인 프롬프트 |
|
||||
| `--source={path}` | 지정된 디렉토리를 소스로 사용 (GitHub 스킵) |
|
||||
| `--local` | 현재 코드베이스를 소스로 사용 (GitHub 스킵) |
|
||||
| `--force` | 버전 비교 스킵, 동일 버전이어도 강제 실행 |
|
||||
|
||||
### Step 4: 다운로드 및 추출
|
||||
|
||||
```text
|
||||
추출 전략 (폴백 체인):
|
||||
1. ZipArchive (PHP zip 확장) → class_exists(ZipArchive::class)
|
||||
2. unzip CLI 명령어 → ZipArchive 미사용 시 폴백
|
||||
|
||||
v접두사 자동 감지 (resolveGithubArchiveUrl):
|
||||
1. "v{version}" 태그로 HEAD 요청 시도 (예: v7.0.0-alpha.15)
|
||||
2. 실패 시 "{version}" 태그로 HEAD 요청 시도 (예: 7.0.0-alpha.15)
|
||||
3. HTTP 200/302 → 유효한 URL 반환
|
||||
4. 모두 실패 → null (업데이트 불가)
|
||||
```
|
||||
|
||||
### Step 5: 백업
|
||||
|
||||
```text
|
||||
- CoreBackupHelper::createBackup() 사용
|
||||
- 백업 대상: config('app.update.targets') + config('app.update.backup_only') + config('app.update.backup_extra')
|
||||
- 제외 패턴: config('app.update.excludes')
|
||||
- 백업 위치: storage 경로에 타임스탬프 디렉토리
|
||||
```
|
||||
|
||||
### Step 6: Composer 최적화
|
||||
|
||||
```text
|
||||
1. composer.json + composer.lock의 MD5 비교 (_pending vs base_path)
|
||||
2. 동일 → "composer 의존성 변경 없음 — 스킵" (Step 6 + Step 8 모두 스킵)
|
||||
3. 변경됨 → composer install --no-dev --optimize-autoloader --no-interaction --no-scripts
|
||||
4. --no-scripts: post-autoload-dump 방지 (Step 11에서 package:discover로 처리)
|
||||
```
|
||||
|
||||
### Step 7: 파일 적용
|
||||
|
||||
```text
|
||||
- _pending 소스에서 config('app.update.targets')에 해당하는 파일/디렉토리만 선택적 덮어쓰기
|
||||
- FilePermissionHelper::copyDirectory() 사용 → 원본 파일 권한 보존
|
||||
- ExtensionPendingHelper::copyToActive() 미사용 (권한 유실 방지)
|
||||
```
|
||||
|
||||
### Step 9: 마이그레이션 + 동기화
|
||||
|
||||
```text
|
||||
1. php artisan migrate --force
|
||||
2. syncCoreRolesAndPermissions() — config/core.php의 roles/permissions 동기화
|
||||
3. syncCoreMenus() — config/core.php의 menus 동기화
|
||||
4. syncCoreMailTemplates() — config/core.php의 mail_templates 동기화
|
||||
```
|
||||
|
||||
> 역할/권한/메뉴 동기화는 `user_overrides` 패턴을 사용하여 사용자 커스터마이징 보존.
|
||||
> 상세: [extension-update-system.md § 13](../extension/extension-update-system.md#13-역할권한메뉴-동기화)
|
||||
|
||||
### Step 10: 업그레이드 스텝
|
||||
|
||||
```text
|
||||
1. upgrades/ 디렉토리 스캔
|
||||
2. Upgrade_X_Y_Z.php 패턴 매칭 → 버전 변환
|
||||
3. fromVersion < stepVersion <= toVersion 범위 필터링
|
||||
4. version_compare 자연 정렬 (오름차순)
|
||||
5. 각 스텝 순차 실행 (UpgradeContext 전달)
|
||||
```
|
||||
|
||||
### Step 11: 마무리
|
||||
|
||||
```text
|
||||
1. .env의 APP_VERSION 갱신
|
||||
2. 캐시 클리어: config, cache, route, view
|
||||
3. bootstrap/cache 파일 삭제 (services.php, packages.php)
|
||||
4. php artisan package:discover 재실행
|
||||
5. php artisan extension:update-autoload (코어 업데이트로 _bundled 변경 가능)
|
||||
6. _pending 디렉토리 삭제
|
||||
7. 성공 시 백업 삭제
|
||||
8. 유지보수 모드 해제
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 백업 및 롤백
|
||||
|
||||
> 파일: `app/Extension/Helpers/CoreBackupHelper.php`
|
||||
|
||||
### 백업 생성
|
||||
|
||||
```text
|
||||
- CoreBackupHelper::createBackup() 호출
|
||||
- 대상: config('app.update.targets') + config('app.update.backup_only') + config('app.update.backup_extra')
|
||||
- 제외: config('app.update.excludes')
|
||||
- 저장: storage 경로에 타임스탬프 디렉토리 (Ymd_His)
|
||||
```
|
||||
|
||||
### 롤백 흐름 (실패 시)
|
||||
|
||||
```text
|
||||
1. Exception 발생
|
||||
2. 백업이 존재하면:
|
||||
├─ CoreUpdateService::restoreFromBackup($backupPath)
|
||||
├─ CoreBackupHelper::restoreFromBackup() → 파일 원복
|
||||
└─ _pending 디렉토리 삭제
|
||||
3. 실패 보고서 생성: storage/logs/core_update_failure_YYYYMMDD_HHMMSS.log
|
||||
4. 업데이트 로그 저장: storage/logs/core_update_failed_YYYYMMDD_HHMMSS.log
|
||||
5. 유지보수 모드 유지 (수동으로 php artisan up 필요)
|
||||
```
|
||||
|
||||
### 롤백 실패 시
|
||||
|
||||
```text
|
||||
- 복원 실패 자체는 예외를 전파하지 않음 (에러 로그만 기록)
|
||||
- 관리자에게 안내: "이전 버전으로 사이트를 운영하려면: php artisan up"
|
||||
- 유지보수 모드 bypass secret 출력
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 마이그레이션 vs 업그레이드 스텝
|
||||
|
||||
```text
|
||||
주의: 마이그레이션과 업그레이드 스텝의 역할을 혼동하지 않을 것
|
||||
```
|
||||
|
||||
| 구분 | 마이그레이션 (`database/migrations/`) | 업그레이드 스텝 (`upgrades/`) |
|
||||
|------|--------------------------------------|-------------------------------|
|
||||
| **역할** | DB 스키마 변경 (컬럼 추가/삭제/변경, 인덱스, 테이블) | 데이터 백필/변환, 설정 마이그레이션 |
|
||||
| **실행 시점** | `php artisan migrate` (설치/업데이트 모두) | `php artisan core:update` Step 10 (업데이트 시만) |
|
||||
| **신규 설치** | 실행됨 | 실행되지 않음 (fromVersion == toVersion) |
|
||||
| **버전 업그레이드** | 실행됨 | 실행됨 (범위 내 스텝만) |
|
||||
| **예시** | `$table->uuid('uuid')->nullable()->after('id')` | 기존 레코드 UUID 백필 + NOT NULL 변환 |
|
||||
|
||||
### 역할 분리 원칙
|
||||
|
||||
```text
|
||||
✅ 마이그레이션: 테이블/컬럼/인덱스 생성·변경·삭제 (스키마)
|
||||
✅ 업그레이드 스텝: 기존 데이터 변환, 백필, 설정 구조 변경 (데이터)
|
||||
|
||||
❌ 마이그레이션에 데이터 백필 로직 포함 금지
|
||||
❌ 업그레이드 스텝에 스키마 변경 포함 금지 (Schema::table 등)
|
||||
단, 백필 후 NOT NULL 제약 추가처럼 데이터 완결성에 필수인 경우는 예외
|
||||
```
|
||||
|
||||
### 신규 설치 시 데이터 초기화
|
||||
|
||||
신규 설치 시 업그레이드 스텝은 실행되지 않으므로, 모델의 `boot()` 이벤트나 Seeder에서 초기 데이터를 생성해야 합니다.
|
||||
|
||||
```php
|
||||
// 예: User 모델 — 신규 레코드 생성 시 UUID 자동 할당
|
||||
protected static function boot(): void
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function (self $user) {
|
||||
if (empty($user->uuid)) {
|
||||
$user->uuid = app(UniqueIdServiceInterface::class)->generateUuid();
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 업그레이드 스텝이 필요한 경우
|
||||
|
||||
| 변경 유형 | 업그레이드 스텝 필요 | 예시 |
|
||||
|----------|-------------------|------|
|
||||
| 기존 데이터 백필/변환 | ✅ | UUID 백필, 형식 변환 |
|
||||
| NOT NULL 제약 추가 (백필 후) | ✅ (예외) | 스키마이지만 데이터 완결성 의존 |
|
||||
| 권한/역할/메뉴 추가·수정 | ❌ (자동 동기화) | config/core.php 수정만으로 충분 |
|
||||
| 정적 권한/메뉴 제거 | ✅ (cleanup 명시 호출) | 기존 메뉴/권한 삭제 |
|
||||
| PHP 코드만 변경 | ❌ | 버그 수정, 성능 개선 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 업그레이드 스텝 작성
|
||||
|
||||
### 디렉토리 구조
|
||||
|
||||
```text
|
||||
upgrades/ # 프로젝트 루트
|
||||
├── .gitkeep
|
||||
├── Upgrade_7_0_0_beta_4.php # 7.0.0-alpha.4
|
||||
└── Upgrade_7_0_0_beta_15.php # 7.0.0-alpha.15
|
||||
```
|
||||
|
||||
### 작성 예시
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 코어 7.0.0-alpha.15 업그레이드 스텝
|
||||
*
|
||||
* 기존 사용자 레코드에 UUID v7을 백필합니다.
|
||||
*/
|
||||
class Upgrade_7_0_0_beta_15 implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
// 1. 사전 조건 확인
|
||||
if (! Schema::hasColumn('users', 'uuid')) {
|
||||
$context->logger->warning('uuid 컬럼 없음. 마이그레이션을 먼저 실행하세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 데이터 백필
|
||||
$nullCount = DB::table('users')->whereNull('uuid')->count();
|
||||
if ($nullCount > 0) {
|
||||
$context->logger->info("UUID 백필 시작: {$nullCount}건");
|
||||
DB::table('users')->whereNull('uuid')->orderBy('id')->chunk(100, function ($users) {
|
||||
foreach ($users as $user) {
|
||||
DB::table('users')
|
||||
->where('id', $user->id)
|
||||
->update(['uuid' => Str::orderedUuid()->toString()]);
|
||||
}
|
||||
});
|
||||
$context->logger->info("UUID 백필 완료");
|
||||
}
|
||||
|
||||
// 3. 백필 완료 후 NOT NULL 제약 (데이터 완결성 예외)
|
||||
// raw SQL에서는 $context->table()로 프리픽스 적용 필수
|
||||
$column = DB::selectOne("SHOW COLUMNS FROM {$context->table('users')} WHERE Field = 'uuid'");
|
||||
if ($column && $column->Null === 'YES') {
|
||||
Schema::table('users', function ($table) {
|
||||
$table->uuid('uuid')->nullable(false)->unique()->change();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 작성 체크리스트
|
||||
|
||||
```text
|
||||
□ UpgradeStepInterface 구현
|
||||
□ 네임스페이스: App\Upgrades
|
||||
□ 파일명: Upgrade_X_Y_Z.php (버전에 맞는 언더스코어 표기)
|
||||
□ 사전 조건 확인 (테이블/컬럼 존재 여부)
|
||||
□ 로거를 통한 진행 상황 기록
|
||||
□ 멱등성 보장 (여러 번 실행해도 안전)
|
||||
□ 대량 데이터는 chunk() 사용
|
||||
□ raw SQL 사용 시 $context->table()로 테이블 프리픽스 적용
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 자동 발견 및 실행 규칙
|
||||
|
||||
> 파일: `app/Services/CoreUpdateService.php` — `runUpgradeSteps()`
|
||||
|
||||
### 발견 프로세스
|
||||
|
||||
```text
|
||||
1. base_path('upgrades') 디렉토리 스캔
|
||||
2. .php 확장자 파일만 대상
|
||||
3. 정규식 매칭: /^Upgrade_(\d+)_(\d+)_(\d+)(?:_([a-zA-Z]\w*(?:_\d+)*))?$/
|
||||
4. 버전 변환: 1_0_0 → 1.0.0, 7_0_0_beta_4 → 7.0.0-alpha.4
|
||||
5. require_once 로딩 → App\Upgrades\{filename} 클래스 인스턴스화
|
||||
6. UpgradeStepInterface 구현 확인
|
||||
```
|
||||
|
||||
### 실행 규칙
|
||||
|
||||
- **필터 조건**: `fromVersion < stepVersion <= toVersion` (`version_compare` 사용)
|
||||
- **정렬**: `uksort($steps, 'version_compare')` — 자연 정렬 오름차순
|
||||
- **실행**: 각 스텝에 `UpgradeContext::withCurrentStep($version)` 불변 복제 전달
|
||||
|
||||
### 버전 네이밍 규칙
|
||||
|
||||
파일명의 언더스코어가 버전 구분자로 변환됩니다:
|
||||
|
||||
| 파일명 | 변환 버전 | 설명 |
|
||||
|--------|----------|------|
|
||||
| `Upgrade_1_0_0.php` | `1.0.0` | 숫자 3자리 |
|
||||
| `Upgrade_7_0_0_beta_4.php` | `7.0.0-alpha.4` | pre-release 포함 |
|
||||
| `Upgrade_7_0_0_beta_15.php` | `7.0.0-alpha.15` | pre-release 2자리 |
|
||||
|
||||
**규칙**: 숫자 3자리(`X_Y_Z`) 후 알파벳으로 시작하는 부분은 `-`로 연결, 이후 `_`는 `.`로 변환
|
||||
|
||||
### UpgradeStepInterface
|
||||
|
||||
> 파일: `app/Contracts/Extension/UpgradeStepInterface.php`
|
||||
|
||||
```php
|
||||
interface UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void;
|
||||
}
|
||||
```
|
||||
|
||||
### UpgradeContext
|
||||
|
||||
> 파일: `app/Extension/UpgradeContext.php`
|
||||
|
||||
```php
|
||||
// readonly 속성
|
||||
public readonly LoggerInterface $logger; // upgrade 로그 채널
|
||||
public readonly string $fromVersion; // 업그레이드 시작 버전
|
||||
public readonly string $toVersion; // 업그레이드 목표 버전
|
||||
public readonly string $currentStep; // 현재 실행 중인 스텝 버전
|
||||
|
||||
// 메서드
|
||||
public function table(string $table): string // DB 프리픽스 적용 (raw SQL용)
|
||||
public function withCurrentStep(string $stepVersion): self // 불변 복제
|
||||
```
|
||||
|
||||
> **raw SQL에서 테이블명 사용 시 `$context->table()` 필수**
|
||||
> - `Schema::hasColumn('users', ...)`, `DB::table('users')` → 프리픽스 자동 적용 (불필요)
|
||||
> - `DB::selectOne("SHOW COLUMNS FROM ...")` 등 raw SQL → **`$context->table('users')` 필수**
|
||||
|
||||
---
|
||||
|
||||
## 7. 버전 관리
|
||||
|
||||
### 버전 소스
|
||||
|
||||
| 파일 | 역할 |
|
||||
|------|------|
|
||||
| `config/app.php` — `'version'` | SSoT (env 기본값 정의) |
|
||||
| `.env` — `APP_VERSION` | 런타임 오버라이드 |
|
||||
| `.env.example` | 배포 템플릿 |
|
||||
|
||||
### 버전 읽기
|
||||
|
||||
```php
|
||||
CoreVersionChecker::getCoreVersion() // → config('app.version')
|
||||
```
|
||||
|
||||
### 버전 갱신 (Step 11)
|
||||
|
||||
```php
|
||||
CoreUpdateService::updateVersionInEnv($version)
|
||||
// .env에 APP_VERSION이 존재하면: 정규식으로 라인 교체
|
||||
// .env에 APP_VERSION이 없으면: "APP_VERSION={version}\n" 추가
|
||||
```
|
||||
|
||||
### 버전 변경 시 필수 동기화
|
||||
|
||||
```text
|
||||
필수: 코어 버전 변경 시 3곳 동기화
|
||||
|
||||
1. config/app.php — env('APP_VERSION', '새버전')
|
||||
2. .env.example — APP_VERSION=새버전
|
||||
3. .env.testing — APP_VERSION=새버전 (테스트 환경)
|
||||
4. CHANGELOG.md — 변경사항 기록
|
||||
```
|
||||
|
||||
### 부트스트랩 호환성 자동 검증
|
||||
|
||||
> 파일: `app/Providers/CoreServiceProvider.php` — `validateAndDeactivateIncompatibleExtensions()`, `validateAndDeactivateIncompatibleTemplates()`
|
||||
|
||||
**애플리케이션 부트(boot) 시마다** CoreServiceProvider가 모든 활성 확장의 `g7_version` 요구사항을 검증합니다.
|
||||
`config('app.version')`이 확장의 요구 버전을 충족하지 않으면 **해당 확장을 자동으로 비활성화**합니다.
|
||||
|
||||
#### 검증 흐름
|
||||
|
||||
```text
|
||||
1. CoreServiceProvider::boot() 실행
|
||||
2. CoreVersionChecker::getCacheKey($type) 캐시 확인 (TTL: 1시간)
|
||||
3. 캐시 없으면 → 모든 활성 확장 순회
|
||||
4. 각 확장의 g7_version (예: ">=7.0.0-beta.1") 확인
|
||||
5. Semver::satisfies(config('app.version'), $constraint) 실행
|
||||
6. false 반환 시 → Manager::deactivateModule/Plugin/Template() 호출
|
||||
7. 캐시 저장 (1시간 유효)
|
||||
```
|
||||
|
||||
#### 주의사항
|
||||
|
||||
| 항목 | 설명 |
|
||||
|------|------|
|
||||
| **검증 주기** | 캐시 만료(1시간)마다 재검증 |
|
||||
| **비활성화 대상** | 호환되지 않는 **모든** 활성 확장 (모듈, 플러그인, 템플릿) |
|
||||
| **activity_log** | 기록되지 않음 (Service 레이어를 거치지 않고 Manager 직접 호출) |
|
||||
| **로그** | `storage/logs/laravel.log`에 warning 기록 |
|
||||
|
||||
#### 버전 확인 방법
|
||||
|
||||
```bash
|
||||
php artisan tinker
|
||||
> \Composer\Semver\Semver::satisfies(config('app.version'), '>=7.0.0-beta.1');
|
||||
```
|
||||
|
||||
#### 버전 우선순위
|
||||
|
||||
```text
|
||||
config('app.version') = env('APP_VERSION', 'config/app.php 기본값')
|
||||
|
||||
.env에 APP_VERSION이 있으면 → .env 값 사용 (config/app.php 기본값 무시)
|
||||
.env에 APP_VERSION이 없으면 → config/app.php의 기본값 사용
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. CoreUpdateService 주요 메서드
|
||||
|
||||
> 파일: `app/Services/CoreUpdateService.php`
|
||||
|
||||
### 업데이트 감지
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `checkForUpdates()` | `(): array` | GitHub API로 최신 릴리스 조회 |
|
||||
| `getChangelog()` | `(?string $from, ?string $to): array` | CHANGELOG.md 파싱, 버전 범위 필터 |
|
||||
| `checkSystemRequirements()` | `(): array` | 추출 도구 검증 (ZipArchive/unzip) |
|
||||
| `validatePendingPath()` | `(): array` | _pending 디렉토리 존재/권한 확인 |
|
||||
|
||||
### 다운로드 및 소스 준비
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `downloadUpdate()` | `(string $version, ?Closure $onProgress): string` | GitHub 다운로드 + 추출 (폴백 체인) |
|
||||
| `copySourceToPending()` | `(string $sourceDir, ?Closure $onProgress): string` | --source 모드: 외부 디렉토리 → _pending 복사 |
|
||||
| `prepareLocalSource()` | `(?Closure $onProgress): string` | --local 모드: 현재 코드 → _pending 복사 |
|
||||
| `validatePendingUpdate()` | `(string $pendingPath): void` | 패키지 구조 검증 (composer.json, app/, config/app.php) |
|
||||
| `createPendingDirectory()` | `(): string` | _pending/core_Ymd_His/ 디렉토리 생성 |
|
||||
| `cleanupPending()` | `(string $pendingPath): void` | _pending 하위 디렉토리 삭제 |
|
||||
|
||||
### 백업 및 복원
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `createBackup()` | `(?Closure $onProgress): string` | CoreBackupHelper로 백업 생성 |
|
||||
| `restoreFromBackup()` | `(string $backupPath, ?Closure $onProgress): void` | 백업에서 파일 복원 |
|
||||
|
||||
### 적용 및 설치
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `applyUpdate()` | `(string $sourcePath, ?Closure $onProgress): void` | _pending → base_path 선택적 덮어쓰기 |
|
||||
| `runComposerInstallInPending()` | `(string $pendingPath, ?Closure $onProgress): void` | _pending에서 composer install (--no-scripts) |
|
||||
| `isComposerUnchangedForCore()` | `(string $pendingPath): bool` | composer.json/lock MD5 비교 |
|
||||
| `runComposerInstall()` | `(?Closure $onProgress): void` | base_path에서 composer install |
|
||||
| `copyVendorFromPending()` | `(string $pendingPath, ?Closure $onProgress): void` | _pending/vendor → base_path/vendor |
|
||||
|
||||
### 마이그레이션 및 동기화
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `runMigrations()` | `(): void` | `php artisan migrate --force` |
|
||||
| `syncCoreRolesAndPermissions()` | `(): void` | config/core.php roles/permissions 동기화 |
|
||||
| `syncCoreMenus()` | `(): void` | config/core.php menus 동기화 |
|
||||
| `syncCoreMailTemplates()` | `(): void` | config/core.php mail_templates 동기화 (user_overrides 보존) |
|
||||
|
||||
### 업그레이드 및 마무리
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `runUpgradeSteps()` | `(string $from, string $to, ?Closure $onStep): void` | upgrades/ 자동 발견 + 실행 |
|
||||
| `updateVersionInEnv()` | `(string $version): void` | .env의 APP_VERSION 갱신 |
|
||||
| `clearAllCaches()` | `(): void` | config/cache/route/view 클리어 + package:discover |
|
||||
|
||||
### 유지보수 모드
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `enableMaintenanceMode()` | `(): string` | `php artisan down --secret` → bypass secret 반환 |
|
||||
| `disableMaintenanceMode()` | `(): void` | `php artisan up` |
|
||||
|
||||
### 유틸리티
|
||||
|
||||
| 메서드 | 시그니처 | 설명 |
|
||||
|--------|---------|------|
|
||||
| `generateFailureReport()` | `(Throwable $e, string $from, string $to): string` | 에러 보고서 생성 → storage/logs/ |
|
||||
|
||||
---
|
||||
|
||||
## 9. Artisan 커맨드
|
||||
|
||||
### core:update
|
||||
|
||||
```bash
|
||||
php artisan core:update [--force] [--no-backup] [--no-maintenance] [--local] [--source={path}]
|
||||
```
|
||||
|
||||
| 옵션 | 설명 |
|
||||
|------|------|
|
||||
| `--force` | 버전 비교 스킵, 동일 버전이어도 강제 업데이트 |
|
||||
| `--no-backup` | 백업 생성 스킵 (Step 5) |
|
||||
| `--no-maintenance` | 유지보수 모드 스킵 (Step 3) |
|
||||
| `--local` | 현재 코드베이스를 소스로 사용 (GitHub 스킵) |
|
||||
| `--source={path}` | 지정 디렉토리를 소스로 사용 (GitHub 스킵) |
|
||||
|
||||
**종료 코드**:
|
||||
- `0` (SUCCESS): 업데이트 성공 또는 이미 최신 버전
|
||||
- `1` (FAILURE): 요건 미충족 또는 업데이트 실패
|
||||
|
||||
### core:check-updates
|
||||
|
||||
```bash
|
||||
php artisan core:check-updates
|
||||
```
|
||||
|
||||
- GitHub API 호출 → 현재/최신 버전 표시
|
||||
- "새로운 업데이트가 있습니다!" 또는 "현재 최신 버전입니다."
|
||||
|
||||
---
|
||||
|
||||
## 10. API 엔드포인트
|
||||
|
||||
> 파일: `app/Http/Controllers/Api/Admin/CoreUpdateController.php`
|
||||
|
||||
| 메서드 | 경로 | 설명 |
|
||||
|--------|------|------|
|
||||
| GET | `/api/admin/core-update/check-updates` | 코어 업데이트 확인 (422 시 check_failed) |
|
||||
| POST | `/api/admin/core-update/changelog` | 코어 변경 로그 조회 (from_version, to_version) |
|
||||
|
||||
> ActivityLog: `checkForUpdates` 호출 시 `core_update.check` 액티비티 기록
|
||||
|
||||
---
|
||||
|
||||
## 11. 설정 (config/app.php)
|
||||
|
||||
### 버전
|
||||
|
||||
```php
|
||||
'version' => env('APP_VERSION', '7.0.0-alpha.14'),
|
||||
```
|
||||
|
||||
### 업데이트 설정
|
||||
|
||||
```php
|
||||
'update' => [
|
||||
'github_url' => '...', // GitHub 리포지토리 URL
|
||||
'github_token' => env('GITHUB_TOKEN'), // GitHub Personal Access Token (선택)
|
||||
'pending_path' => '...', // _pending 디렉토리 경로
|
||||
'targets' => [...], // 업데이트 적용 + 백업 대상 파일/디렉토리
|
||||
'backup_only' => ['vendor'], // 백업/복원 전용 (applyUpdate 제외)
|
||||
'backup_extra' => [...], // 추가 백업 대상
|
||||
'excludes' => [...], // 제외 패턴
|
||||
],
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. 에러 처리 및 로깅
|
||||
|
||||
### 시스템 요건 검증
|
||||
|
||||
```text
|
||||
- ZipArchive 또는 unzip 명령어 중 하나 이상 필요
|
||||
- 미충족 시 커맨드 실패 (EXIT 1) + 사용 가능 방법 목록 출력
|
||||
```
|
||||
|
||||
### _pending 검증
|
||||
|
||||
```text
|
||||
- 디렉토리 미존재: File::ensureDirectoryExists() 시도
|
||||
- 쓰기 불가: 경로, 소유자, 그룹, 권한 정보 포함 에러 출력
|
||||
```
|
||||
|
||||
### 패키지 검증
|
||||
|
||||
```text
|
||||
- 필수 파일: composer.json, app/ 디렉토리, config/app.php
|
||||
- config/app.php에 'version' 키 필수
|
||||
- 미충족 시 RuntimeException
|
||||
```
|
||||
|
||||
### Composer 실패
|
||||
|
||||
```text
|
||||
- exit code 비정상 → RuntimeException (마지막 5줄 출력 포함)
|
||||
```
|
||||
|
||||
### 로그 위치
|
||||
|
||||
| 로그 | 경로 | 내용 |
|
||||
|------|------|------|
|
||||
| 성공 로그 | `storage/logs/core_update_success_YYYYMMDD_HHMMSS.log` | 전체 실행 타임라인 |
|
||||
| 실패 로그 | `storage/logs/core_update_failed_YYYYMMDD_HHMMSS.log` | 실패까지의 실행 타임라인 |
|
||||
| 실패 보고서 | `storage/logs/core_update_failure_YYYYMMDD_HHMMSS.log` | 예외 상세 + 시스템 정보 |
|
||||
| 일반 로그 | `storage/logs/laravel.log` | Log 파사드 통한 기록 |
|
||||
|
||||
---
|
||||
|
||||
## 13. 유지보수 모드
|
||||
|
||||
### 활성화 (Step 3)
|
||||
|
||||
```php
|
||||
Artisan::call('down', [
|
||||
'--secret' => $secret, // UUID 토큰 (bypass 접근용)
|
||||
'--retry' => 60, // Retry-After 헤더 (초)
|
||||
'--refresh' => 15, // 브라우저 자동 새로고침 (초)
|
||||
]);
|
||||
```
|
||||
|
||||
### Bypass 접근
|
||||
|
||||
```text
|
||||
URL: https://example.com/{secret}
|
||||
→ 쿠키 발급 → 유지보수 모드에서도 접근 가능
|
||||
```
|
||||
|
||||
### 해제
|
||||
|
||||
```text
|
||||
- 성공 시: Step 11에서 자동 해제 (php artisan up)
|
||||
- 실패 시: 유지보수 모드 유지 → 관리자에게 수동 해제 안내
|
||||
"이전 버전으로 사이트를 운영하려면: php artisan up"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. 코어 vs 확장 업데이트 비교
|
||||
|
||||
| 항목 | 코어 | 모듈/플러그인 | 템플릿 |
|
||||
|------|------|-------------|--------|
|
||||
| **소스** | GitHub releases (zipball) | GitHub 또는 _bundled | GitHub 또는 _bundled |
|
||||
| **추출** | 폴백 체인 (ZipArchive → unzip) | ExtensionPendingHelper | ExtensionPendingHelper |
|
||||
| **백업** | CoreBackupHelper (선택) | ExtensionBackupHelper (선택) | ExtensionBackupHelper (선택) |
|
||||
| **유지보수 모드** | 전체 앱 down (secret 토큰) | 없음 | 없음 |
|
||||
| **Composer** | MD5 비교 → 변경 시만 실행 | 확장별 독립 vendor/ | 해당 없음 |
|
||||
| **파일 적용** | FilePermissionHelper (권한 보존) | ExtensionPendingHelper::copyToActive() | ExtensionPendingHelper::copyToActive() |
|
||||
| **vendor 처리** | 변경 시 전체 복사 | 확장별 composer install | 해당 없음 |
|
||||
| **마이그레이션** | 필수 (Step 9) | 선택 (확장별) | 없음 |
|
||||
| **동기화** | roles + permissions + menus + mail templates | roles + permissions + menus | 없음 |
|
||||
| **업그레이드 스텝** | `upgrades/Upgrade_X_Y_Z.php` | `{ext}/upgrades/Upgrade_X_Y_Z.php` | 없음 |
|
||||
| **네임스페이스** | `App\Upgrades` | `Modules\Vendor\Module\Upgrades` | 해당 없음 |
|
||||
| **실행 주체** | `CoreUpdateService` | `AbstractModule` | `TemplateManager` |
|
||||
| **커맨드** | `core:update` | `module:update {id}` | `template:update {id}` |
|
||||
| **레이아웃** | 해당 없음 | 자동 갱신 | 충돌 전략 (apply_new/keep_current) |
|
||||
| **롤백** | 전체 복원 + 유지보수 유지 | 확장별 복원 + 상태 복원 | 확장별 복원 |
|
||||
| **로깅** | 타임스탬프 성공/실패 로그 + 실패 보고서 | laravel.log | laravel.log |
|
||||
|
||||
---
|
||||
|
||||
## 참고 파일 위치
|
||||
|
||||
| 파일 | 경로 |
|
||||
|------|------|
|
||||
| CoreUpdateCommand | `app/Console/Commands/Core/CoreUpdateCommand.php` |
|
||||
| CoreCheckUpdatesCommand | `app/Console/Commands/Core/CoreCheckUpdatesCommand.php` |
|
||||
| CoreUpdateService | `app/Services/CoreUpdateService.php` |
|
||||
| CoreUpdateController | `app/Http/Controllers/Api/Admin/CoreUpdateController.php` |
|
||||
| CoreVersionChecker | `app/Extension/CoreVersionChecker.php` |
|
||||
| CoreBackupHelper | `app/Extension/Helpers/CoreBackupHelper.php` |
|
||||
| UpgradeStepInterface | `app/Contracts/Extension/UpgradeStepInterface.php` |
|
||||
| UpgradeContext | `app/Extension/UpgradeContext.php` |
|
||||
| 코어 업그레이드 디렉토리 | `upgrades/` |
|
||||
| 코어 설정 | `config/app.php` (version, update 섹션) |
|
||||
| 역할/권한/메뉴 정의 | `config/core.php` |
|
||||
@@ -0,0 +1,343 @@
|
||||
# Enum 사용 규칙
|
||||
|
||||
> **관련 문서**: [백엔드 가이드 인덱스](./index.md) | [검증 로직](./validation.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 상태/타입/분류 = Enum 필수 (PHP 8.1+ Backed Enum)
|
||||
2. 위치: app/Enums/ 또는 modules/*/src/Enums/
|
||||
3. DB: enum 컬럼 또는 string + 검증
|
||||
4. FormRequest: Rule::enum(StatusEnum::class) 사용
|
||||
5. cases(): 모든 값 조회, tryFrom(): 안전한 변환
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
- [핵심 원칙](#핵심-원칙)
|
||||
- [Enum 사용 대상](#enum-사용-대상)
|
||||
- [잘못된 예시](#잘못된-예시)
|
||||
- [올바른 예시](#올바른-예시)
|
||||
- [파일 위치](#파일-위치)
|
||||
- [데이터베이스 연동](#데이터베이스-연동)
|
||||
- [FormRequest 검증에서 사용](#formrequest-검증에서-사용)
|
||||
- [개발 체크리스트](#개발-체크리스트)
|
||||
|
||||
---
|
||||
|
||||
## 핵심 원칙
|
||||
|
||||
```text
|
||||
상태, 타입, 분류 등 제한된 값 집합은 반드시 Enum으로 정의
|
||||
✅ 필수: PHP 8.1+ Backed Enum 사용
|
||||
```
|
||||
|
||||
**핵심 원칙**:
|
||||
|
||||
- **타입 안전성**: 문자열/정수 대신 Enum 사용으로 타입 안전성 확보
|
||||
- **자동완성**: IDE의 자동완성 지원으로 개발 생산성 향상
|
||||
- **유지보수**: 값 변경 시 한 곳에서만 수정
|
||||
- **유효성 검증**: 잘못된 값 입력 방지
|
||||
|
||||
---
|
||||
|
||||
## Enum 사용 대상
|
||||
|
||||
| 상황 | 예시 | Enum 사용 |
|
||||
|------|------|----------|
|
||||
| 상태 값 | active, inactive, pending | ✅ 필수 |
|
||||
| 타입 구분 | template, module, plugin | ✅ 필수 |
|
||||
| 고정 옵션 | admin, user, guest | ✅ 필수 |
|
||||
| 가변 데이터 | 사용자 입력, 동적 값 | ❌ 불필요 |
|
||||
|
||||
---
|
||||
|
||||
## 잘못된 예시
|
||||
|
||||
```php
|
||||
// ❌ 문자열 직접 사용 - 타입 안전성 없음
|
||||
class Module
|
||||
{
|
||||
public function setStatus(string $status): void
|
||||
{
|
||||
$this->status = $status; // 'actve' 오타 가능
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ 상수로 정의 - 타입 체크 불가
|
||||
class ModuleStatus
|
||||
{
|
||||
public const ACTIVE = 'active';
|
||||
public const INACTIVE = 'inactive';
|
||||
}
|
||||
|
||||
$module->setStatus('invalid'); // 오류 없이 통과
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 올바른 예시
|
||||
|
||||
```php
|
||||
// ✅ Backed Enum 정의
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 확장(모듈, 플러그인, 템플릿) 상태 Enum
|
||||
*/
|
||||
enum ExtensionStatus: string
|
||||
{
|
||||
/**
|
||||
* 활성화됨
|
||||
*/
|
||||
case Active = 'active';
|
||||
|
||||
/**
|
||||
* 비활성화됨
|
||||
*/
|
||||
case Inactive = 'inactive';
|
||||
|
||||
/**
|
||||
* 설치 중
|
||||
*/
|
||||
case Installing = 'installing';
|
||||
|
||||
/**
|
||||
* 제거 중
|
||||
*/
|
||||
case Uninstalling = 'uninstalling';
|
||||
|
||||
/**
|
||||
* 제거됨 (미설치 상태)
|
||||
*/
|
||||
case Uninstalled = 'uninstalled';
|
||||
|
||||
/**
|
||||
* 업데이트 중
|
||||
*/
|
||||
case Updating = 'updating';
|
||||
|
||||
/**
|
||||
* 모든 상태 값을 문자열 배열로 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 상태 값인지 확인
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 타입 힌팅으로 안전하게 사용
|
||||
class Module
|
||||
{
|
||||
public function setStatus(ExtensionStatus $status): void
|
||||
{
|
||||
$this->status = $status->value;
|
||||
}
|
||||
}
|
||||
|
||||
$module->setStatus(ExtensionStatus::Active); // 타입 안전
|
||||
$module->setStatus('invalid'); // 컴파일 오류!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 파일 위치
|
||||
|
||||
```text
|
||||
app/Enums/ # 코어 Enum
|
||||
├── ExtensionStatus.php # 확장 상태
|
||||
├── LayoutSourceType.php # 레이아웃 소스 타입
|
||||
├── ScopeType.php # 권한 스코프 타입
|
||||
└── UserRole.php # 사용자 역할
|
||||
|
||||
modules/[vendor-module]/src/Enums/ # 모듈 Enum
|
||||
```
|
||||
|
||||
### ScopeType Enum — 권한 스코프
|
||||
|
||||
역할별 권한의 접근 범위를 정의합니다. `role_permissions` 피벗 테이블의 `scope_type` 컬럼에서 사용됩니다.
|
||||
|
||||
```php
|
||||
enum ScopeType: string
|
||||
{
|
||||
/** 본인 리소스만 접근 */
|
||||
case Self = 'self';
|
||||
|
||||
/** 소유 역할 공유 사용자의 리소스 접근 */
|
||||
case Role = 'role';
|
||||
}
|
||||
// null = 전체 접근 (제한 없음)
|
||||
```
|
||||
|
||||
**scope_type 값과 의미**:
|
||||
|
||||
| 값 | 의미 | 목록 필터링 | 상세 접근 체크 |
|
||||
| ---- | -------------- | ----------------------------------------- | -------------- |
|
||||
| `null` | 전체 접근 | 필터 미적용 | 항상 통과 |
|
||||
| `'self'` | 본인 리소스만 | `WHERE {owner_key} = {user_id}` | 소유자 일치 체크 |
|
||||
| `'role'` | 소유역할 범위 | `WHERE {owner_key} IN (역할 공유 사용자)` | 역할 공유 체크 |
|
||||
|
||||
**union 정책** (복수 역할 보유 시): `null`(전체) > `'role'`(소유역할) > `'self'`(본인) — 가장 넓은 범위 적용
|
||||
|
||||
> 상세: [permissions.md](../extension/permissions.md) scope_type 시스템 참조
|
||||
|
||||
---
|
||||
|
||||
## 데이터베이스 연동
|
||||
|
||||
```php
|
||||
// 마이그레이션에서 Enum 값 사용
|
||||
use App\Enums\ExtensionStatus;
|
||||
|
||||
$table->string('status')->default(ExtensionStatus::Inactive->value)
|
||||
->comment('상태: ' . implode(', ', ExtensionStatus::values()));
|
||||
|
||||
// 모델에서 캐스팅
|
||||
protected $casts = [
|
||||
'status' => ExtensionStatus::class,
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FormRequest 검증에서 사용
|
||||
|
||||
```php
|
||||
use App\Enums\ExtensionStatus;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'status' => ['required', Rule::enum(ExtensionStatus::class)],
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Enum 표준 헬퍼 메서드
|
||||
|
||||
G7에서 Enum에 추가하는 표준 헬퍼 메서드입니다.
|
||||
|
||||
### 필수 메서드
|
||||
|
||||
```php
|
||||
enum UserStatus: string
|
||||
{
|
||||
case Active = 'active';
|
||||
case Inactive = 'inactive';
|
||||
case Blocked = 'blocked';
|
||||
case Withdrawn = 'withdrawn';
|
||||
|
||||
/**
|
||||
* 모든 상태 값을 문자열 배열로 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 값인지 확인
|
||||
*
|
||||
* @param string $value 검증할 값
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 라벨 반환
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return __('user.status.' . $this->value);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 선택 메서드 (UI 연동 시)
|
||||
|
||||
```php
|
||||
/**
|
||||
* CSS variant 반환 (Badge, Tag 등에서 사용)
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function variant(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Active => 'success',
|
||||
self::Inactive => 'warning',
|
||||
self::Blocked => 'danger',
|
||||
self::Withdrawn => 'secondary',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 아이콘 클래스 반환
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function icon(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Active => 'fa-check-circle',
|
||||
self::Inactive => 'fa-pause-circle',
|
||||
self::Blocked => 'fa-ban',
|
||||
self::Withdrawn => 'fa-user-slash',
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### 메서드 요약
|
||||
|
||||
| 메서드 | 유형 | 필수 | 용도 |
|
||||
| ------ | ------ | ------ | ------ |
|
||||
| `values()` | static | ✅ | 마이그레이션 comment, 검증 등 |
|
||||
| `isValid()` | static | ✅ | 값 유효성 검증 |
|
||||
| `label()` | instance | ✅ | API 응답의 다국어 라벨 |
|
||||
| `variant()` | instance | 선택 | UI Badge/Tag 스타일 매핑 |
|
||||
| `icon()` | instance | 선택 | UI 아이콘 매핑 |
|
||||
|
||||
---
|
||||
|
||||
## 개발 체크리스트
|
||||
|
||||
- [ ] Backed Enum 사용 (string 또는 int)
|
||||
- [ ] 각 case에 한국어 PHPDoc 주석 추가
|
||||
- [ ] `values()` 헬퍼 메서드 구현
|
||||
- [ ] `isValid()` 헬퍼 메서드 구현 (필요시)
|
||||
- [ ] 마이그레이션 comment에 가능한 값 명시
|
||||
- [ ] 모델에서 Enum 캐스팅 설정
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [검증 로직](./validation.md) - FormRequest에서 Enum 검증
|
||||
- [데이터베이스 가이드](../database-guide.md) - 마이그레이션 규칙
|
||||
- [백엔드 가이드 인덱스](./index.md) - 전체 목차
|
||||
@@ -0,0 +1,322 @@
|
||||
# Custom Exception 다국어 처리
|
||||
|
||||
> 이 문서는 G7에서 Custom Exception 클래스의 다국어 처리 방법을 설명합니다.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 예외 메시지 하드코딩 금지 → __() 함수 필수
|
||||
2. 메시지 위치: lang/ko/exceptions.php, lang/en/exceptions.php
|
||||
3. 파라미터 치환: __('exceptions.key', ['param' => $value])
|
||||
4. 코어 예외: exceptions.template_engine.* 형식
|
||||
5. 모듈 예외: vendor-module::exceptions.* 형식
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [핵심 원칙](#핵심-원칙)
|
||||
2. [다국어 파일 위치 및 구조](#다국어-파일-위치-및-구조)
|
||||
3. [파라미터 치환 패턴](#파라미터-치환-패턴)
|
||||
4. [템플릿 엔진 Custom Exception 예시](#템플릿-엔진-custom-exception-예시)
|
||||
5. [Custom Exception 개발 체크리스트](#custom-exception-개발-체크리스트)
|
||||
6. [관련 문서](#관련-문서)
|
||||
|
||||
---
|
||||
|
||||
## 핵심 원칙
|
||||
|
||||
```
|
||||
필수: __() 함수 사용 (예외 메시지 하드코딩 금지)
|
||||
필수: __() 함수를 사용한 다국어 처리
|
||||
```
|
||||
|
||||
### 필수 규칙
|
||||
|
||||
- **모든 예외 메시지는 다국어 파일에 정의**: `/lang/ko/exceptions.php`, `/lang/en/exceptions.php`
|
||||
- **Exception 생성자에서 __() 함수 사용**: 하드코딩된 문자열 사용 금지
|
||||
- **파라미터 치환 지원**: `:trace`, `:max`, `:id` 등의 동적 값 지원
|
||||
- **일관성 유지**: 모든 커스텀 예외가 동일한 패턴 사용
|
||||
|
||||
---
|
||||
|
||||
## 다국어 파일 위치 및 구조
|
||||
|
||||
### 파일 위치
|
||||
|
||||
```
|
||||
/lang/ko/exceptions.php # 한국어 예외 메시지
|
||||
/lang/en/exceptions.php # 영어 예외 메시지
|
||||
```
|
||||
|
||||
### 파일 구조 예시
|
||||
|
||||
```php
|
||||
// /lang/ko/exceptions.php
|
||||
return [
|
||||
'circular_reference' => '레이아웃 순환 참조 감지: :trace',
|
||||
'max_depth_exceeded' => '레이아웃 중첩 깊이가 최대 허용 깊이(:max)를 초과했습니다.',
|
||||
'resource_not_found' => ':resource를 찾을 수 없습니다.',
|
||||
];
|
||||
|
||||
// /lang/en/exceptions.php
|
||||
return [
|
||||
'circular_reference' => 'Layout circular reference detected: :trace',
|
||||
'max_depth_exceeded' => 'Layout nesting depth exceeds maximum allowed depth (:max).',
|
||||
'resource_not_found' => ':resource not found.',
|
||||
];
|
||||
```
|
||||
|
||||
### 중첩 구조 (네임스페이스 그룹화)
|
||||
|
||||
```php
|
||||
// /lang/ko/exceptions.php
|
||||
return [
|
||||
'template' => [
|
||||
'circular_reference' => '레이아웃 순환 참조 감지: :trace',
|
||||
'max_depth_exceeded' => '레이아웃 중첩 깊이(:current)가 최대 허용 깊이(:max)를 초과했습니다.',
|
||||
'template_not_found' => '템플릿을 찾을 수 없습니다: :identifier',
|
||||
'layout_not_found' => '레이아웃을 찾을 수 없습니다: :layout_name',
|
||||
'component_not_found' => '컴포넌트를 찾을 수 없습니다: :component_name',
|
||||
'invalid_layout_structure' => '유효하지 않은 레이아웃 구조입니다.',
|
||||
],
|
||||
];
|
||||
|
||||
// /lang/en/exceptions.php
|
||||
return [
|
||||
'template' => [
|
||||
'circular_reference' => 'Layout circular reference detected: :trace',
|
||||
'max_depth_exceeded' => 'Layout nesting depth (:current) exceeds maximum allowed depth (:max).',
|
||||
'template_not_found' => 'Template not found: :identifier',
|
||||
'layout_not_found' => 'Layout not found: :layout_name',
|
||||
'component_not_found' => 'Component not found: :component_name',
|
||||
'invalid_layout_structure' => 'Invalid layout structure.',
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 파라미터 치환 패턴
|
||||
|
||||
### 잘못된 예시 (DON'T)
|
||||
|
||||
```php
|
||||
// ❌ 하드코딩된 예외 메시지 - 금지
|
||||
class CircularReferenceException extends Exception
|
||||
{
|
||||
public function __construct(array $stack, string $currentLayout)
|
||||
{
|
||||
$stackTrace = implode(' → ', $stack) . " → {$currentLayout}";
|
||||
$message = "레이아웃 순환 참조 감지: {$stackTrace}"; // 한국어만 지원, 다국어 불가
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 올바른 예시 (DO)
|
||||
|
||||
```php
|
||||
// ✅ 다국어 함수 사용 (파라미터 치환)
|
||||
class CircularReferenceException extends Exception
|
||||
{
|
||||
private array $stack;
|
||||
|
||||
public function __construct(array $stack, string $currentLayout)
|
||||
{
|
||||
$this->stack = $stack;
|
||||
|
||||
// ✅ 다국어 함수 사용 (파라미터 치환)
|
||||
$stackTrace = implode(' → ', $stack) . " → {$currentLayout}";
|
||||
$message = __('exceptions.circular_reference', ['trace' => $stackTrace]);
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public function getStack(): array
|
||||
{
|
||||
return $this->stack;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 다중 파라미터 처리
|
||||
|
||||
```php
|
||||
class MaxDepthExceededException extends Exception
|
||||
{
|
||||
public function __construct(int $currentDepth, int $maxDepth)
|
||||
{
|
||||
// ✅ 다국어 함수 사용 (다중 파라미터)
|
||||
$message = __('exceptions.max_depth_exceeded', [
|
||||
'current' => $currentDepth,
|
||||
'max' => $maxDepth
|
||||
]);
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 템플릿 엔진 Custom Exception 예시
|
||||
|
||||
### CircularReferenceException (레이아웃 순환 참조)
|
||||
|
||||
템플릿 레이아웃 상속 시 순환 참조가 발생하면 이 예외를 발생시킵니다.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions\Template;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* 레이아웃 순환 참조 예외
|
||||
*/
|
||||
class CircularReferenceException extends Exception
|
||||
{
|
||||
private array $stack;
|
||||
|
||||
public function __construct(array $stack, string $currentLayout)
|
||||
{
|
||||
$this->stack = $stack;
|
||||
|
||||
// ✅ 다국어 함수 사용
|
||||
$stackTrace = implode(' → ', $stack) . " → {$currentLayout}";
|
||||
$message = __('exceptions.template.circular_reference', ['trace' => $stackTrace]);
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 순환 참조 스택 반환
|
||||
*/
|
||||
public function getStack(): array
|
||||
{
|
||||
return $this->stack;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### MaxDepthExceededException (레이아웃 깊이 초과)
|
||||
|
||||
레이아웃 상속 깊이가 최대 허용 깊이(10)를 초과하면 이 예외를 발생시킵니다.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions\Template;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* 레이아웃 최대 깊이 초과 예외
|
||||
*/
|
||||
class MaxDepthExceededException extends Exception
|
||||
{
|
||||
private int $currentDepth;
|
||||
private int $maxDepth;
|
||||
|
||||
public function __construct(int $currentDepth, int $maxDepth = 10)
|
||||
{
|
||||
$this->currentDepth = $currentDepth;
|
||||
$this->maxDepth = $maxDepth;
|
||||
|
||||
// ✅ 다국어 함수 사용 (다중 파라미터)
|
||||
$message = __('exceptions.template.max_depth_exceeded', [
|
||||
'current' => $currentDepth,
|
||||
'max' => $maxDepth
|
||||
]);
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 깊이 반환
|
||||
*/
|
||||
public function getCurrentDepth(): int
|
||||
{
|
||||
return $this->currentDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최대 허용 깊이 반환
|
||||
*/
|
||||
public function getMaxDepth(): int
|
||||
{
|
||||
return $this->maxDepth;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Service에서 사용 예시 (LayoutService)
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Services\Template;
|
||||
|
||||
use App\Exceptions\Template\CircularReferenceException;
|
||||
use App\Exceptions\Template\MaxDepthExceededException;
|
||||
|
||||
class LayoutService
|
||||
{
|
||||
private const MAX_DEPTH = 10;
|
||||
|
||||
/**
|
||||
* 레이아웃 병합 (상속 체인 처리)
|
||||
*
|
||||
* @throws CircularReferenceException 순환 참조 발생 시
|
||||
* @throws MaxDepthExceededException 깊이 초과 시
|
||||
*/
|
||||
public function mergeLayouts(string $layoutName, array $stack = [], int $depth = 0): array
|
||||
{
|
||||
// 순환 참조 검사
|
||||
if (in_array($layoutName, $stack)) {
|
||||
throw new CircularReferenceException($stack, $layoutName);
|
||||
}
|
||||
|
||||
// 깊이 검사
|
||||
if ($depth > self::MAX_DEPTH) {
|
||||
throw new MaxDepthExceededException($depth, self::MAX_DEPTH);
|
||||
}
|
||||
|
||||
// 재귀적으로 레이아웃 병합
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom Exception 개발 체크리스트
|
||||
|
||||
새로운 Custom Exception을 개발할 때 다음 항목을 확인하세요:
|
||||
|
||||
- [ ] `/lang/ko/exceptions.php`에 한국어 메시지 추가
|
||||
- [ ] `/lang/en/exceptions.php`에 영어 메시지 추가
|
||||
- [ ] Exception 생성자에서 모든 메시지는 `__()` 함수 사용
|
||||
- [ ] 동적 값은 파라미터 배열로 전달 (예: `['trace' => $stackTrace]`)
|
||||
- [ ] 두 언어 모두에서 테스트 수행
|
||||
- [ ] 예외 메시지가 사용자에게 노출될 경우 보안 정보 포함 금지
|
||||
|
||||
### 새 Exception 추가 절차
|
||||
|
||||
1. **다국어 키 정의**: 적절한 네임스페이스로 그룹화
|
||||
2. **Exception 클래스 생성**: `__()` 함수로 메시지 생성
|
||||
3. **필요한 속성 저장**: 디버깅이나 로깅에 필요한 값 보관
|
||||
4. **getter 메서드 제공**: 저장된 속성에 접근할 수 있도록 제공
|
||||
5. **테스트 작성**: 두 언어 환경에서 메시지 확인
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [validation.md](./validation.md) - Custom Rule 다국어 처리
|
||||
- [index.md](./index.md) - 백엔드 가이드 인덱스
|
||||
@@ -0,0 +1,395 @@
|
||||
# 미들웨어 등록 규칙
|
||||
|
||||
> **참조**: [백엔드 가이드 인덱스](index.md) | [인증 시스템](authentication.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 인증 필요 미들웨어 → 전역 등록 금지!
|
||||
2. 그룹 등록: appendToGroup('web'|'api', [...])
|
||||
3. 실행 순서: 전역 → 그룹(web/api) → 라우트 → 컨트롤러
|
||||
4. permission 미들웨어: scope_type 기반 접근 제어 (except/only/menu 옵션 폐기)
|
||||
5. scope 체크: Permission.resource_route_key + owner_key + role_permissions.scope_type
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
- [핵심 원칙](#핵심-원칙)
|
||||
- [미들웨어 실행 순서](#미들웨어-실행-순서)
|
||||
- [미들웨어 등록 방식](#미들웨어-등록-방식)
|
||||
- [올바른 등록 예시](#올바른-등록-예시)
|
||||
- [문제 상황과 해결책](#문제-상황과-해결책)
|
||||
- [디버깅 방법](#디버깅-방법)
|
||||
- [미들웨어 개발 체크리스트](#미들웨어-개발-체크리스트)
|
||||
- [관련 파일](#관련-파일)
|
||||
|
||||
---
|
||||
|
||||
## 핵심 원칙
|
||||
|
||||
```text
|
||||
필수: 인증 필요 미들웨어는 appendToGroup('api') 사용 (전역 등록 금지)
|
||||
필수: appendToGroup('web'|'api', [...])으로 그룹 미들웨어에 등록
|
||||
```
|
||||
|
||||
**핵심 이해사항**:
|
||||
|
||||
- **미들웨어 실행 순서**: 전역 미들웨어는 web/api 그룹 미들웨어보다 **먼저** 실행됨
|
||||
- **인증 미들웨어 위치**: Sanctum 인증 미들웨어는 api 그룹에 등록되어 있음
|
||||
- **결과**: 전역 미들웨어에서 `Auth::check()`, `Auth::user()`를 호출하면 항상 `false`/`null` 반환
|
||||
|
||||
---
|
||||
|
||||
## 미들웨어 실행 순서
|
||||
|
||||
```
|
||||
요청 → 전역 미들웨어 → 그룹 미들웨어(web/api) → 라우트 미들웨어 → 컨트롤러
|
||||
↑ ↑
|
||||
Auth 불가능 Auth 가능
|
||||
(인증 전) (인증 후)
|
||||
```
|
||||
|
||||
### 실행 순서 상세
|
||||
|
||||
1. **전역 미들웨어** (`append()`, `prepend()`)
|
||||
- 모든 요청에 대해 가장 먼저 실행
|
||||
- 인증 처리 전이므로 `Auth::check()` = `false`
|
||||
|
||||
2. **그룹 미들웨어** (`appendToGroup('web'|'api', ...)`)
|
||||
- web 또는 api 그룹에 속한 라우트에서 실행
|
||||
- Sanctum 인증 미들웨어 이후 실행
|
||||
- `Auth::check()` 사용 가능
|
||||
|
||||
3. **라우트 미들웨어** (`alias()`)
|
||||
- 특정 라우트에만 적용
|
||||
- 가장 마지막에 실행
|
||||
|
||||
---
|
||||
|
||||
## 미들웨어 등록 방식
|
||||
|
||||
### 등록 방식 비교 표
|
||||
|
||||
| 방식 | 실행 시점 | Auth 사용 | 사용 사례 |
|
||||
|------|----------|----------|----------|
|
||||
| `append()` | 인증 **전** | ❌ 불가 | CORS, 로깅 등 |
|
||||
| `prepend()` | 인증 **전** (최우선) | ❌ 불가 | 보안 헤더 등 |
|
||||
| `appendToGroup('api', ...)` | 인증 **후** | ✅ 가능 | 사용자별 설정 |
|
||||
| `appendToGroup('web', ...)` | 인증 **후** | ✅ 가능 | 사용자별 설정 |
|
||||
| `alias()` | 라우트 지정 시 | ✅ 가능 | 권한 체크 등 |
|
||||
|
||||
### append vs appendToGroup 차이
|
||||
|
||||
| 구분 | `append()` | `appendToGroup()` |
|
||||
|------|-----------|-------------------|
|
||||
| **등록 위치** | 전역 미들웨어 스택 | 특정 그룹 미들웨어 스택 |
|
||||
| **실행 시점** | 모든 요청의 최초 | 그룹 미들웨어 순서에 따름 |
|
||||
| **인증 상태** | 인증 전 | 인증 후 (Sanctum 이후) |
|
||||
| **적용 범위** | 모든 라우트 | 해당 그룹(web/api) 라우트만 |
|
||||
|
||||
---
|
||||
|
||||
## 올바른 등록 예시
|
||||
|
||||
### bootstrap/app.php
|
||||
|
||||
```php
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
// ✅ SetLocale, SetTimezone은 인증 후 실행되어야 사용자 설정을 읽을 수 있음
|
||||
$localeTimezoneMiddleware = [
|
||||
\App\Http\Middleware\SetLocale::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
];
|
||||
$middleware->appendToGroup('web', $localeTimezoneMiddleware);
|
||||
$middleware->appendToGroup('api', $localeTimezoneMiddleware);
|
||||
|
||||
// 권한 관련 미들웨어 등록 (별칭)
|
||||
$middleware->alias([
|
||||
'admin' => \App\Http\Middleware\AdminMiddleware::class,
|
||||
'permission' => \App\Http\Middleware\PermissionMiddleware::class,
|
||||
'start.api.session' => \App\Http\Middleware\StartApiSession::class,
|
||||
]);
|
||||
})
|
||||
```
|
||||
|
||||
> **참고**: `EnsureFrontendRequestsAreStateful` (stateful)은 제거되었습니다. API 인증은 Bearer 토큰 전용이며, 세션은 `start.api.session` 미들웨어로 로그인/로그아웃 라우트에서만 생성됩니다. 상세: [authentication.md](authentication.md)
|
||||
|
||||
---
|
||||
|
||||
## permission 미들웨어 — scope_type 기반 접근 제어
|
||||
|
||||
> **변경 이력**: `except:`, `only:`, `menu:` 옵션은 scope_type 시스템으로 대체되어 **폐기**되었습니다. (2026-03-10)
|
||||
|
||||
### 문법
|
||||
|
||||
```text
|
||||
permission:{type},{permission}[,{requireAll}]
|
||||
```
|
||||
|
||||
옵션 파라미터 없이 권한 타입과 식별자만 전달합니다.
|
||||
|
||||
### 처리 흐름
|
||||
|
||||
```text
|
||||
1. 권한 타입 검증 (admin/user)
|
||||
2. 동적 파라미터 치환 ({slug} → 실제 값)
|
||||
3. 권한 체크 (인증/게스트)
|
||||
→ 권한 없음 → 403
|
||||
→ 권한 있음 → Step 4로 진행
|
||||
|
||||
4. scope_type 스코프 체크:
|
||||
a. Permission 조회 (static 캐시) → resource_route_key, owner_key
|
||||
b. resource_route_key가 null → 통과 (시스템 리소스)
|
||||
c. $request->route(resource_route_key) → Model resolve
|
||||
d. Model 없음 → 통과 (list 엔드포인트)
|
||||
e. 사용자의 effective scope 확인 (union 정책)
|
||||
f. scope=null → 통과 (전체 접근)
|
||||
g. scope='self' → $model->{owner_key} === $user->id → 아니면 403
|
||||
h. scope='role' → 리소스 소유자가 내 역할을 공유하는지 → 아니면 403
|
||||
```
|
||||
|
||||
### scope_type 값 정의
|
||||
|
||||
| 값 | 의미 | 상세 접근 체크 | 목록 필터링 |
|
||||
|---|---|---|---|
|
||||
| `null` | 전체 접근 (제한 없음) | 항상 통과 | 필터 미적용 |
|
||||
| `'self'` | 본인 리소스만 | `$model->{owner_key} === $user->id` | `WHERE {owner_key} = {user_id}` |
|
||||
| `'role'` | 내 역할 범위 리소스 | 리소스 소유자가 내 역할 공유 | `WHERE {owner_key} IN (역할 공유 사용자 IDs)` |
|
||||
|
||||
### union 정책 (복수 역할 보유 시)
|
||||
|
||||
```text
|
||||
우선순위: null(전체) > 'role'(소유역할) > 'self'(본인)
|
||||
|
||||
- 여러 역할 중 하나라도 scope_type=null → 전체 접근
|
||||
- 전부 non-null이면 가장 넓은 범위 적용 (role > self)
|
||||
- 예: 역할A(scope=self) + 역할B(scope=role) → role 적용
|
||||
```
|
||||
|
||||
### DB 구조
|
||||
|
||||
```text
|
||||
permissions 테이블:
|
||||
- resource_route_key VARCHAR(50) NULL — 라우트 파라미터명 (예: 'user', 'menu', 'product')
|
||||
- owner_key VARCHAR(50) NULL — 소유자 식별 컬럼 (예: 'id', 'created_by', 'user_id')
|
||||
|
||||
role_permissions 피벗:
|
||||
- scope_type ENUM('self', 'role') NULL DEFAULT NULL
|
||||
```
|
||||
|
||||
### 사용 예시
|
||||
|
||||
```php
|
||||
// 권한만 체크 (scope는 DB 설정에 따라 자동 적용)
|
||||
Route::get('{user}', [AdminUserController::class, 'show'])
|
||||
->middleware('permission:admin,core.users.read');
|
||||
|
||||
Route::put('{user}', [AdminUserController::class, 'update'])
|
||||
->middleware('permission:admin,core.users.update');
|
||||
|
||||
Route::put('{menu}', [AdminMenuController::class, 'update'])
|
||||
->middleware('permission:admin,core.menus.update');
|
||||
```
|
||||
|
||||
### 목록 엔드포인트 필터링
|
||||
|
||||
미들웨어는 모델 바인딩이 없는 목록 엔드포인트를 **통과**시킵니다.
|
||||
목록 필터링은 **Repository**에서 `PermissionHelper::applyPermissionScope()`로 처리합니다.
|
||||
|
||||
```php
|
||||
// Repository에서 한 줄로 적용
|
||||
$query = User::query();
|
||||
PermissionHelper::applyPermissionScope($query, 'core.users.read');
|
||||
```
|
||||
|
||||
### 관련 핵심 메서드
|
||||
|
||||
| 메서드 | 위치 | 용도 |
|
||||
|--------|------|------|
|
||||
| `PermissionHelper::checkScopeAccess()` | 미들웨어 (상세 접근) | 모델 바인딩된 리소스의 scope 체크 |
|
||||
| `PermissionHelper::applyPermissionScope()` | Repository (목록 필터링) | 쿼리에 scope WHERE 조건 추가 |
|
||||
| `User::getEffectiveScopeForPermission()` | 모델 | union 정책에 따른 effective scope 반환 |
|
||||
|
||||
### resource_route_key/owner_key가 null인 권한
|
||||
|
||||
시스템 리소스 (ActivityLog, Module, Plugin, Template, Permission, Settings 등)는 `resource_route_key`와 `owner_key`가 null이므로 scope 체크가 자동 스킵됩니다.
|
||||
|
||||
### 폐기된 옵션 (DEPRECATED)
|
||||
|
||||
```text
|
||||
아래 옵션들은 제거되었습니다. 사용 시 미들웨어가 인식하지 않습니다.
|
||||
|
||||
- except:self:{param} → scope_type='self'로 대체
|
||||
- except:owner:{param} → scope_type='self'로 대체
|
||||
- only:self:{param} → scope_type='self'로 대체
|
||||
- only:owner:{param} → scope_type='self'로 대체
|
||||
- menu:{slug} → 제거 (메뉴 접근 제어는 scope_type으로 불필요)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## OptionalSanctumMiddleware (선택적 인증)
|
||||
|
||||
공개 API이면서 인증된 사용자에게는 추가 정보를 제공해야 하는 경우 사용합니다.
|
||||
|
||||
### 동작 흐름
|
||||
|
||||
```text
|
||||
요청 → Bearer 토큰 확인
|
||||
├── 토큰 없음 → guest로 통과
|
||||
├── 토큰 유효 → Sanctum 인증 진행 (인증된 사용자)
|
||||
├── 토큰 만료 → guest로 통과 (공개 페이지 접근 허용)
|
||||
└── 토큰 무효(위조) → 401 Unauthorized
|
||||
```
|
||||
|
||||
### 등록 방식
|
||||
|
||||
```php
|
||||
// bootstrap/app.php
|
||||
$middleware->alias([
|
||||
'optional.sanctum' => \App\Http\Middleware\OptionalSanctumMiddleware::class,
|
||||
]);
|
||||
```
|
||||
|
||||
### 사용 예시
|
||||
|
||||
```php
|
||||
// 레이아웃 API: 비회원도 접근 가능하지만, 인증 사용자에게는 권한 기반 UI 제공
|
||||
Route::middleware('optional.sanctum')
|
||||
->get('/layouts/{name}.json', [LayoutController::class, 'show']);
|
||||
```
|
||||
|
||||
### 일반 Sanctum과의 차이
|
||||
|
||||
| 상황 | `auth:sanctum` | `optional.sanctum` |
|
||||
| ------ | -------------- | -------------------- |
|
||||
| 토큰 없음 | 401 | guest 통과 |
|
||||
| 토큰 유효 | 인증 | 인증 |
|
||||
| 토큰 만료 | 401 | guest 통과 |
|
||||
| 토큰 무효 | 401 | 401 |
|
||||
|
||||
### 구현 파일
|
||||
|
||||
- `app/Http/Middleware/OptionalSanctumMiddleware.php`
|
||||
|
||||
---
|
||||
|
||||
## 문제 상황과 해결책
|
||||
|
||||
### ❌ 잘못된 예시 - 전역 미들웨어로 등록
|
||||
|
||||
```php
|
||||
// ❌ DON'T: 전역 미들웨어로 등록 - 인증 전에 실행됨
|
||||
$middleware->append([
|
||||
\App\Http\Middleware\SetLocale::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
]);
|
||||
|
||||
// SetTimezone 미들웨어 내부
|
||||
if (Auth::check()) { // 항상 false! Sanctum 인증 전이므로
|
||||
return Auth::user()->timezone;
|
||||
}
|
||||
```
|
||||
|
||||
### ✅ 올바른 예시 - 그룹 미들웨어로 등록
|
||||
|
||||
```php
|
||||
// ✅ DO: 그룹 미들웨어로 등록 - 인증 후에 실행됨
|
||||
$middleware->appendToGroup('web', [
|
||||
\App\Http\Middleware\SetLocale::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
]);
|
||||
$middleware->appendToGroup('api', [
|
||||
\App\Http\Middleware\SetLocale::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
]);
|
||||
|
||||
// SetTimezone 미들웨어 내부
|
||||
if (Auth::check()) { // ✅ 정상 작동! Sanctum 인증 후이므로
|
||||
return Auth::user()->timezone;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 디버깅 방법
|
||||
|
||||
미들웨어에서 인증 상태 확인이 필요할 때:
|
||||
|
||||
```php
|
||||
// 미들웨어 내부에 로그 추가
|
||||
\Log::info('Middleware debug', [
|
||||
'auth_check' => Auth::check(),
|
||||
'user_id' => Auth::id(),
|
||||
'user_timezone' => Auth::user()?->timezone,
|
||||
]);
|
||||
```
|
||||
|
||||
### 디버깅 결과 해석
|
||||
|
||||
| `auth_check` 값 | 의미 | 조치 |
|
||||
|----------------|------|------|
|
||||
| `false` | 인증 전에 미들웨어 실행됨 | `appendToGroup()`으로 변경 |
|
||||
| `true` | 정상적으로 인증 후 실행됨 | 문제 없음 |
|
||||
|
||||
---
|
||||
|
||||
## 미들웨어 개발 체크리스트
|
||||
|
||||
### 신규 미들웨어 개발 시
|
||||
|
||||
- [ ] `Auth::check()` 또는 `Auth::user()` 사용 여부 확인
|
||||
- [ ] 인증 필요 시 `appendToGroup('web'|'api', ...)` 사용
|
||||
- [ ] 인증 불필요 시 `append()` 또는 `prepend()` 사용
|
||||
- [ ] 로그로 인증 상태 검증
|
||||
- [ ] web과 api 그룹 모두에 등록 필요 여부 확인
|
||||
|
||||
### 등록 위치 결정 가이드
|
||||
|
||||
```
|
||||
미들웨어에서 Auth 사용?
|
||||
├── YES → appendToGroup('web'|'api', ...)
|
||||
└── NO → append() 또는 prepend()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 관련 파일
|
||||
|
||||
- `bootstrap/app.php`: 미들웨어 등록
|
||||
- `app/Http/Middleware/PermissionMiddleware.php`: permission 미들웨어 (scope_type 체크 포함)
|
||||
- `app/Helpers/PermissionHelper.php`: checkScopeAccess, applyPermissionScope 메서드
|
||||
- `app/Models/User.php`: getEffectiveScopeForPermission (union 정책)
|
||||
- `app/Http/Middleware/StartApiSession.php`: API 세션 미들웨어 (로그인/로그아웃 전용)
|
||||
- `app/Http/Middleware/SetLocale.php`: 로케일 설정 미들웨어
|
||||
- `app/Http/Middleware/SetTimezone.php`: 타임존 설정 미들웨어
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [권한 시스템](../extension/permissions.md) - scope_type 시스템 상세, resource_route_key/owner_key 매핑
|
||||
- [인증 시스템](authentication.md) - Sanctum 인증 및 세션 처리
|
||||
- [서비스 프로바이더 안전성](service-provider.md) - 프로바이더 등록 규칙
|
||||
- [백엔드 가이드 인덱스](index.md) - 전체 가이드 목록
|
||||
|
||||
---
|
||||
|
||||
## 참고 이력
|
||||
|
||||
- [SetTimezone 미들웨어 리팩토링](../../history/20251127_1402_SetTimezone미들웨어리팩토링.md)
|
||||
|
||||
### SEO 미들웨어
|
||||
|
||||
| 항목 | 값 |
|
||||
|------|-----|
|
||||
| 클래스 | `App\Seo\SeoMiddleware` |
|
||||
| 별칭 | `seo` |
|
||||
| 등록 위치 | User catch-all 라우트 그룹에만 |
|
||||
| 금지 | 전역 등록 / Admin 라우트 부착 |
|
||||
|
||||
> 상세: [seo-system.md](seo-system.md)
|
||||
@@ -0,0 +1,185 @@
|
||||
# 알림 시스템 (Notification System)
|
||||
|
||||
> 그누보드7 알림 시스템의 아키텍처와 확장 가이드
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 모든 알림은 BaseNotification 상속 필수 (via() 보일러플레이트 제거)
|
||||
2. getHookPrefix() + getNotificationType() 구현 → 훅명 자동 생성
|
||||
3. toMail()은 각 서브클래스가 직접 구현 (Laravel 규약)
|
||||
4. 각 모듈은 자체 Mailable 클래스 소유 (AuthNotificationMail, BoardNotificationMail)
|
||||
5. 채널 확장: 플러그인이 Filter 훅으로 via() 채널 추가
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 개요
|
||||
|
||||
### BaseNotification 추상 클래스
|
||||
|
||||
```text
|
||||
BaseNotification (abstract)
|
||||
├── getHookPrefix(): string → 'core.auth', 'sirsoft-board', 'sirsoft-ecommerce'
|
||||
├── getNotificationType(): string → 'welcome', 'new_comment', 'order_confirmed'
|
||||
└── via(): array → HookManager::applyFilters() 자동 호출
|
||||
```
|
||||
|
||||
**위치**: `app/Notifications/BaseNotification.php`
|
||||
|
||||
**역할**: `via()` 메서드만 추상화. `toMail()`은 각 서브클래스가 직접 구현.
|
||||
|
||||
### 훅 이름 규칙
|
||||
|
||||
```text
|
||||
{hookPrefix}.notification.channels
|
||||
```
|
||||
|
||||
| 모듈 | hookPrefix | 훅명 |
|
||||
|------|-----------|------|
|
||||
| 코어 인증 | `core.auth` | `core.auth.notification.channels` |
|
||||
| 게시판 | `sirsoft-board` | `sirsoft-board.notification.channels` |
|
||||
| 이커머스 | `sirsoft-ecommerce` | `sirsoft-ecommerce.notification.channels` |
|
||||
|
||||
---
|
||||
|
||||
## 코어 알림 클래스
|
||||
|
||||
### 인증 알림 (app/Notifications/Auth/)
|
||||
|
||||
| 클래스 | hookPrefix | notificationType | Mailable |
|
||||
|--------|-----------|-----------------|----------|
|
||||
| WelcomeNotification | `core.auth` | `welcome` | AuthNotificationMail |
|
||||
| ResetPasswordNotification | `core.auth` | `reset_password` | AuthNotificationMail |
|
||||
| PasswordChangedNotification | `core.auth` | `password_changed` | AuthNotificationMail |
|
||||
|
||||
### 게시판 알림 (modules/sirsoft-board/src/Notifications/)
|
||||
|
||||
| 클래스 | hookPrefix | notificationType | Mailable |
|
||||
|--------|-----------|-----------------|----------|
|
||||
| NewCommentNotification | `sirsoft-board` | `new_comment` | BoardNotificationMail |
|
||||
| ReplyCommentNotification | `sirsoft-board` | `reply_comment` | BoardNotificationMail |
|
||||
| PostReplyNotification | `sirsoft-board` | `post_reply` | BoardNotificationMail |
|
||||
| PostActionNotification | `sirsoft-board` | `post_action` | BoardNotificationMail |
|
||||
| NewPostAdminNotification | `sirsoft-board` | `new_post_admin` | BoardNotificationMail |
|
||||
|
||||
---
|
||||
|
||||
## 새 알림 클래스 작성법
|
||||
|
||||
### 1. BaseNotification 상속
|
||||
|
||||
```php
|
||||
namespace Modules\Sirsoft\Ecommerce\Notifications;
|
||||
|
||||
use App\Notifications\BaseNotification;
|
||||
use Modules\Sirsoft\Ecommerce\Mail\EcommerceNotificationMail;
|
||||
|
||||
class OrderConfirmedNotification extends BaseNotification
|
||||
{
|
||||
public function __construct(
|
||||
private Order $order
|
||||
) {}
|
||||
|
||||
protected function getHookPrefix(): string
|
||||
{
|
||||
return 'sirsoft-ecommerce';
|
||||
}
|
||||
|
||||
protected function getNotificationType(): string
|
||||
{
|
||||
return 'order_confirmed';
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): EcommerceNotificationMail
|
||||
{
|
||||
return new EcommerceNotificationMail(
|
||||
type: 'order_confirmed',
|
||||
order: $this->order,
|
||||
recipient: $notifiable
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Mailable 클래스는 모듈별 소유
|
||||
|
||||
각 모듈은 자체 Mailable 클래스를 만듭니다. 데이터 형태가 모듈마다 근본적으로 다르기 때문입니다.
|
||||
|
||||
| 모듈 | Mailable | 주요 프로퍼티 |
|
||||
|------|----------|-------------|
|
||||
| 코어 인증 | AuthNotificationMail | type, recipient, actionUrl, extraData |
|
||||
| 게시판 | BoardNotificationMail | type, board, post, comment, recipient, commentAuthorName, actionType |
|
||||
| 이커머스 | (직접 구현) | type, order, recipient, ... |
|
||||
|
||||
---
|
||||
|
||||
## 채널 확장 (플러그인)
|
||||
|
||||
### Filter 훅으로 채널 추가
|
||||
|
||||
```php
|
||||
// plugins/sirsoft-site-notification/src/Listeners/SiteNotificationListener.php
|
||||
class SiteNotificationListener implements HookListenerInterface
|
||||
{
|
||||
public function getSubscribedHooks(): array
|
||||
{
|
||||
return [
|
||||
'core.auth.notification.channels' => [
|
||||
'method' => 'addDatabaseChannel',
|
||||
'type' => 'filter', // type: 'filter' 필수!
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function addDatabaseChannel(array $channels, string $type, object $notifiable): array
|
||||
{
|
||||
$channels[] = 'database';
|
||||
return $channels;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 커스텀 채널 클래스 (FCM, 카카오톡 등)
|
||||
|
||||
```php
|
||||
// via()에 FQCN 추가 → Laravel이 자동 resolve
|
||||
$channels[] = \Plugins\Sirsoft\Push\Channels\FcmChannel::class;
|
||||
```
|
||||
|
||||
커스텀 채널 클래스는 `send(object $notifiable, Notification $notification)` 메서드를 구현합니다.
|
||||
|
||||
---
|
||||
|
||||
## 테스트
|
||||
|
||||
### BaseNotificationTest
|
||||
|
||||
**위치**: `tests/Unit/Notifications/BaseNotificationTest.php`
|
||||
|
||||
| 테스트 | 검증 항목 |
|
||||
|--------|----------|
|
||||
| extends_laravel_notification | Notification 상속 확인 |
|
||||
| via_returns_mail_channel_by_default | 기본 ['mail'] 반환 |
|
||||
| hook_can_add_channels | Filter 훅으로 채널 추가 |
|
||||
| hook_receives_notification_type | 훅에 type 전달 확인 |
|
||||
| hook_receives_notifiable | 훅에 notifiable 전달 확인 |
|
||||
| hook_name_format | 훅 이름 형식 확인 |
|
||||
| board_module_hook_prefix | 모듈 훅 접두사 확인 |
|
||||
|
||||
### 기존 알림 테스트 (수정 없이 통과)
|
||||
|
||||
- `WelcomeNotificationTest` (6건)
|
||||
- `ResetPasswordNotificationTest` (7건)
|
||||
- `PasswordChangedNotificationTest` (6건)
|
||||
|
||||
---
|
||||
|
||||
## 금지 사항
|
||||
|
||||
```text
|
||||
❌ BaseNotification 없이 Notification 직접 상속
|
||||
❌ via()에서 HookManager 직접 호출 (BaseNotification이 처리)
|
||||
❌ Mailable 추상화 (모듈별 데이터 형태가 다름)
|
||||
❌ 훅 type: 'filter' 누락 (반환값 무시됨)
|
||||
```
|
||||
@@ -0,0 +1,595 @@
|
||||
# API 응답 규칙 (ResponseHelper)
|
||||
|
||||
> **관련 문서**: [index.md](index.md) | [controllers.md](controllers.md) | [api-resources.md](api-resources.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 모든 API 응답은 ResponseHelper 사용
|
||||
2. 인수 순서: success($messageKey, $data) - 메시지가 먼저!
|
||||
3. 데이터 소스 API: dataSource() 메서드 사용
|
||||
4. 페이지네이션: paginated() 또는 LengthAwarePaginator
|
||||
5. 에러: error($messageKey, $statusCode)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [ResponseHelper 사용](#responsehelper-사용)
|
||||
2. [데이터 소스용 API](#데이터-소스용-api-)
|
||||
3. [응답 구조](#응답-구조)
|
||||
4. [프론트엔드 바인딩](#프론트엔드-바인딩)
|
||||
5. [구현 예시](#구현-예시)
|
||||
6. [인증 처리](#인증-처리)
|
||||
7. [성능 최적화](#성능-최적화)
|
||||
8. [에러 처리](#에러-처리)
|
||||
9. [페이지네이션 처리](#페이지네이션-처리-)
|
||||
10. [라우트/쿼리 파라미터 처리](#라우트쿼리-파라미터-처리)
|
||||
11. [체크리스트](#체크리스트)
|
||||
12. [안티 패턴 vs 모범 사례](#안티-패턴-vs-모범-사례)
|
||||
13. [HTTP 캐시 (ETag, 304 Not Modified)](#http-캐시-etag-304-not-modified)
|
||||
|
||||
---
|
||||
|
||||
## ResponseHelper 사용
|
||||
|
||||
### 규칙
|
||||
|
||||
- 모든 API 응답은 ResponseHelper 사용
|
||||
- 일관된 응답 구조 유지
|
||||
|
||||
### 메서드 시그니처
|
||||
|
||||
```
|
||||
주의: 인수 순서 확인!
|
||||
success($messageKey, $data) - 메시지가 먼저!
|
||||
❌ success($data, $messageKey) - 잘못된 순서
|
||||
```
|
||||
|
||||
```php
|
||||
// 성공 응답
|
||||
ResponseHelper::success(
|
||||
string $messageKey = 'messages.success', // 첫 번째: 메시지 키
|
||||
mixed $data = null, // 두 번째: 데이터
|
||||
int $statusCode = 200,
|
||||
array $messageParams = [],
|
||||
string $domain = 'core'
|
||||
);
|
||||
|
||||
// 오류 응답
|
||||
ResponseHelper::error(
|
||||
string $messageKey = 'messages.failed', // 첫 번째: 메시지 키
|
||||
int $statusCode = 400,
|
||||
mixed $errors = null,
|
||||
array $messageParams = [],
|
||||
string $domain = 'core'
|
||||
);
|
||||
|
||||
// 검증 오류
|
||||
ResponseHelper::validationError($errors, $messageKey = 'messages.validation_failed');
|
||||
|
||||
// 404 응답
|
||||
ResponseHelper::notFound($messageKey = 'messages.not_found');
|
||||
|
||||
// 401 응답
|
||||
ResponseHelper::unauthorized($messageKey = 'messages.unauthorized');
|
||||
|
||||
// 403 응답
|
||||
ResponseHelper::forbidden($messageKey = 'messages.forbidden');
|
||||
|
||||
// 500 응답
|
||||
ResponseHelper::serverError($messageKey = 'messages.error_occurred', $error = null);
|
||||
```
|
||||
|
||||
### 사용 예시
|
||||
|
||||
```php
|
||||
// ✅ 올바른 사용
|
||||
return ResponseHelper::success('messages.success', $data);
|
||||
return ResponseHelper::success('plugins.settings.updated', $settings);
|
||||
|
||||
// ❌ 잘못된 사용 - TypeError 발생!
|
||||
return ResponseHelper::success($data, 'messages.success'); // 인수 순서 틀림
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 데이터 소스용 API ⭐
|
||||
|
||||
**정의**: 템플릿 레이아웃 JSON의 `data_sources`에서 호출되는 API 엔드포인트
|
||||
|
||||
**목적**:
|
||||
- 프론트엔드 레이아웃 렌더링 시 필요한 데이터 제공
|
||||
- DataSourceManager를 통한 자동 fetch 지원
|
||||
- Progressive loading을 통한 빠른 초기 렌더링
|
||||
|
||||
### 필수 요구사항
|
||||
|
||||
```
|
||||
필수: 데이터 소스용 API는 아래 규칙 준수
|
||||
필수: ResponseHelper 사용
|
||||
✅ 필수: 인증 필요 시 auth_required: true 설정
|
||||
✅ 권장: 응답 시간 200ms 이내
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 응답 구조
|
||||
|
||||
데이터 소스용 API는 반드시 `ResponseHelper::success()`를 사용하여 다음 형태로 응답해야 합니다:
|
||||
|
||||
```php
|
||||
// 표준 응답 구조
|
||||
return ResponseHelper::success('messages.success', $data);
|
||||
|
||||
// 실제 응답 JSON
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
// 실제 데이터 (이 부분이 프론트엔드에서 {{dataSourceId.data}}로 바인딩됨)
|
||||
},
|
||||
"message": null,
|
||||
"error": null
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 프론트엔드 바인딩
|
||||
|
||||
```json
|
||||
{
|
||||
"data_sources": [
|
||||
{
|
||||
"id": "admin_menu",
|
||||
"endpoint": "/api/admin/menus"
|
||||
}
|
||||
],
|
||||
"components": [
|
||||
{
|
||||
"props": {
|
||||
"menu": "{{admin_menu.data}}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
위 예시에서 `{{admin_menu.data}}`는 API 응답의 `data` 필드를 참조합니다.
|
||||
|
||||
---
|
||||
|
||||
## 구현 예시
|
||||
|
||||
### 기본 컨트롤러 구현
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Services\MenuService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class MenuController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private MenuService $menuService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 관리자 메뉴 목록 조회 (데이터 소스용)
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
// 1. 서비스에서 데이터 조회
|
||||
$menus = $this->menuService->getAdminMenus();
|
||||
|
||||
// 2. ResponseHelper로 응답 (필수)
|
||||
return ResponseHelper::success('messages.success', $menus);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API 리소스 사용 예시
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin\Auth;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Resources\Admin\UserResource;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class AuthController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* 현재 인증된 사용자 정보 조회 (데이터 소스용)
|
||||
*/
|
||||
public function user(): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// API 리소스로 변환 후 ResponseHelper 사용
|
||||
return ResponseHelper::success('messages.success', new UserResource($user));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 인증 처리
|
||||
|
||||
데이터 소스에서 `auth_required: true`로 설정된 경우:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "current_user",
|
||||
"type": "api",
|
||||
"endpoint": "/api/admin/auth/user",
|
||||
"auth_required": true
|
||||
}
|
||||
```
|
||||
|
||||
백엔드에서는 라우트에 인증 미들웨어를 반드시 적용해야 합니다:
|
||||
|
||||
```php
|
||||
// routes/api.php
|
||||
Route::middleware(['auth:sanctum', 'type:admin'])->group(function () {
|
||||
Route::get('/admin/auth/user', [AuthController::class, 'user']);
|
||||
Route::get('/admin/menus', [MenuController::class, 'index']);
|
||||
Route::get('/admin/notifications', [NotificationController::class, 'index']);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 성능 최적화
|
||||
|
||||
데이터 소스 API는 레이아웃 로딩 시 자동으로 호출되므로 성능이 중요합니다:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class MenuService
|
||||
{
|
||||
/**
|
||||
* 관리자 메뉴 조회 (캐싱 적용)
|
||||
*/
|
||||
public function getAdminMenus(): array
|
||||
{
|
||||
// 1. 캐시 사용 (권장)
|
||||
return Cache::remember('admin_menus', 3600, function () {
|
||||
return $this->repository->getActiveMenus();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* N+1 쿼리 방지
|
||||
*/
|
||||
public function getMenusWithPermissions(): array
|
||||
{
|
||||
// 2. Eager Loading 사용
|
||||
return $this->repository
|
||||
->with(['permissions', 'children'])
|
||||
->where('active', true)
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 에러 처리
|
||||
|
||||
데이터 소스 API에서 에러 발생 시:
|
||||
|
||||
```php
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
try {
|
||||
$data = $this->service->getData();
|
||||
return ResponseHelper::success('messages.success', $data);
|
||||
} catch (\Exception $e) {
|
||||
// 에러 로그 기록
|
||||
Log::error('Failed to fetch data source', [
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
// 클라이언트에 에러 응답
|
||||
return ResponseHelper::error(
|
||||
__('messages.failed_to_load_data'),
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
프론트엔드에서는:
|
||||
- `loading_strategy: "progressive"`: 에러 발생 시에도 렌더링 계속 (빈 데이터)
|
||||
- `loading_strategy: "blocking"`: 에러 발생 시 빈 데이터로 렌더링
|
||||
- `DataSourceManagerOptions.onError` 콜백으로 에러 핸들링
|
||||
|
||||
---
|
||||
|
||||
## 페이지네이션 처리 ⭐
|
||||
|
||||
목록 API에서 페이지네이션 사용 시, 반드시 `pagination` 객체로 분리하여 반환:
|
||||
|
||||
```php
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = $request->input('per_page', 15);
|
||||
$page = $request->input('page', 1);
|
||||
|
||||
$users = $this->userService->getPaginatedUsers($perPage, $page);
|
||||
|
||||
// ✅ 표준 페이지네이션 응답 구조
|
||||
return ResponseHelper::success('messages.success', [
|
||||
'data' => $users->items(),
|
||||
'pagination' => [
|
||||
'total' => $users->total(),
|
||||
'from' => $users->firstItem() ?? 0,
|
||||
'to' => $users->lastItem() ?? 0,
|
||||
'per_page' => $users->perPage(),
|
||||
'current_page' => $users->currentPage(),
|
||||
'last_page' => $users->lastPage(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
### 프론트엔드 바인딩 경로
|
||||
|
||||
```json
|
||||
{
|
||||
"text": "$t:admin.users.pagination_info|total={{users?.data?.pagination?.total ?? 0}}|from={{users?.data?.pagination?.from ?? 0}}|to={{users?.data?.pagination?.to ?? 0}}"
|
||||
}
|
||||
```
|
||||
|
||||
> **주의**: `data.pagination.total`이 올바른 경로입니다. `data.data.total`이 아님!
|
||||
|
||||
---
|
||||
|
||||
## 라우트/쿼리 파라미터 처리
|
||||
|
||||
데이터 소스에서 파라미터 바인딩:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "product_detail",
|
||||
"endpoint": "/api/admin/products/{{route.id}}",
|
||||
"params": {
|
||||
"include": "{{query.include}}"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
백엔드 컨트롤러:
|
||||
|
||||
```php
|
||||
public function show(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$include = $request->input('include', []);
|
||||
|
||||
$product = $this->productService->getProductById($id, $include);
|
||||
|
||||
if (!$product) {
|
||||
return ResponseHelper::notFound('messages.product_not_found');
|
||||
}
|
||||
|
||||
return ResponseHelper::success('messages.success', $product);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 체크리스트
|
||||
|
||||
데이터 소스용 API 구현 시 반드시 확인:
|
||||
|
||||
```
|
||||
□ ResponseHelper::success() 사용
|
||||
□ auth_required: true 시 인증 미들웨어 적용
|
||||
□ 응답 시간 200ms 이내 (캐싱, Eager Loading 등)
|
||||
□ N+1 쿼리 방지
|
||||
□ API 리소스로 데이터 변환 (일관성)
|
||||
□ 에러 핸들링 (try-catch)
|
||||
□ 페이지네이션 표준 구조
|
||||
□ 로깅 (에러 발생 시)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 안티 패턴 vs 모범 사례
|
||||
|
||||
### 안티 패턴
|
||||
|
||||
```php
|
||||
// ❌ DON'T: ResponseHelper 미사용
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$data = $this->service->getData();
|
||||
return response()->json(['data' => $data]); // 구조 불일치
|
||||
}
|
||||
|
||||
// ❌ DON'T: 직접 배열 반환
|
||||
public function index(): array
|
||||
{
|
||||
return $this->service->getData(); // JsonResponse 타입 위반
|
||||
}
|
||||
|
||||
// ❌ DON'T: 인증 미들웨어 누락
|
||||
// auth_required: true인데 라우트에 인증 미들웨어 없음
|
||||
Route::get('/admin/menus', [MenuController::class, 'index']); // 취약점
|
||||
|
||||
// ❌ DON'T: 느린 응답 (500ms+)
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$data = $this->repository->all(); // N+1 쿼리 발생
|
||||
return ResponseHelper::success('messages.success', $data);
|
||||
}
|
||||
```
|
||||
|
||||
### 모범 사례
|
||||
|
||||
```php
|
||||
// ✅ DO: 완전한 구현 예시
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Resources\Admin\MenuResource;
|
||||
use App\Services\MenuService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class MenuController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private MenuService $menuService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 관리자 메뉴 목록 조회
|
||||
*
|
||||
* 데이터 소스에서 사용:
|
||||
* - endpoint: /api/admin/menus
|
||||
* - auth_required: true
|
||||
* - loading_strategy: progressive
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 1. 서비스에서 캐시된 데이터 조회
|
||||
$menus = $this->menuService->getAdminMenus();
|
||||
|
||||
// 2. API 리소스로 변환 (일관성)
|
||||
$resource = MenuResource::collection($menus);
|
||||
|
||||
// 3. ResponseHelper로 응답 (필수)
|
||||
return ResponseHelper::success('messages.success', $resource);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
// 4. 에러 로그 기록
|
||||
Log::error('Failed to load admin menus', [
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
// 5. 에러 응답 (프론트엔드에서 처리)
|
||||
return ResponseHelper::error(
|
||||
__('messages.failed_to_load_menus'),
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## HTTP 캐시 (ETag, 304 Not Modified)
|
||||
|
||||
정적 데이터나 변경 빈도가 낮은 API에는 HTTP 캐시를 적용하여 전송 효율성을 높일 수 있습니다.
|
||||
|
||||
### successWithCache 사용
|
||||
|
||||
`BaseApiController`에서 제공하는 `successWithCache()` 메서드를 사용합니다:
|
||||
|
||||
```php
|
||||
// 캐시 헤더와 함께 성공 응답 반환
|
||||
return $this->successWithCache(
|
||||
'messages.success', // 메시지 키
|
||||
$data, // 응답 데이터
|
||||
3600 // 캐시 TTL (초, 기본: 1시간)
|
||||
);
|
||||
```
|
||||
|
||||
### 동작 방식
|
||||
|
||||
1. **첫 요청**: ETag 생성 → 200 OK + `ETag`, `Cache-Control` 헤더
|
||||
2. **재요청**: 클라이언트가 `If-None-Match` 헤더로 ETag 전송
|
||||
3. **ETag 일치**: 304 Not Modified (본문 없음, 헤더만)
|
||||
4. **ETag 불일치**: 새 데이터와 함께 200 OK
|
||||
|
||||
### 응답 헤더
|
||||
|
||||
```http
|
||||
HTTP/1.1 200 OK
|
||||
Cache-Control: max-age=3600, public
|
||||
ETag: "7d74afa3f6f8c8a3992772a87b3475b1"
|
||||
Vary: Accept-Encoding, Accept-Language
|
||||
```
|
||||
|
||||
### 적용 대상
|
||||
|
||||
| 적합 | 부적합 |
|
||||
| ---------------- | ------------------ |
|
||||
| 레이아웃 JSON | 실시간 데이터 |
|
||||
| 메뉴 목록 | 사용자별 데이터 |
|
||||
| 설정/환경값 | 자주 변경되는 목록 |
|
||||
| 번역 데이터 | 인증 정보 |
|
||||
|
||||
### PublicLayoutController 예시
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
|
||||
class PublicLayoutController extends PublicBaseController
|
||||
{
|
||||
private const CACHE_TTL = 3600;
|
||||
|
||||
public function serve(string $templateId, string $layoutName): JsonResponse|Response
|
||||
{
|
||||
// 서버 측 캐싱
|
||||
$mergedLayout = $this->cached(
|
||||
"layout.{$templateId}.{$layoutName}",
|
||||
fn () => $this->layoutService->loadAndMergeLayout($templateId, $layoutName),
|
||||
self::CACHE_TTL
|
||||
);
|
||||
|
||||
// HTTP 캐시 헤더 (ETag, Cache-Control) 포함 응답
|
||||
return $this->successWithCache(
|
||||
'messages.layout_served',
|
||||
$mergedLayout,
|
||||
self::CACHE_TTL
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 관련 메서드 (BaseApiController)
|
||||
|
||||
| 메서드 | 설명 |
|
||||
| ---------------------------------------------- | -------------------------------- |
|
||||
| `generateETag($data)` | 데이터 기반 ETag 생성 |
|
||||
| `isNotModified($etag)` | 클라이언트 캐시 유효성 확인 |
|
||||
| `notModifiedResponse($etag, $maxAge)` | 304 응답 반환 |
|
||||
| `successWithCache($message, $data, $maxAge)` | ETag + Cache-Control 포함 응답 |
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [index.md](index.md) - 백엔드 가이드 인덱스
|
||||
- [controllers.md](controllers.md) - 컨트롤러 계층 구조
|
||||
- [api-resources.md](api-resources.md) - API 리소스 규칙
|
||||
- [routing.md](routing.md) - 라우트 네이밍 및 경로
|
||||
@@ -0,0 +1,277 @@
|
||||
# 라우트 네이밍 및 경로
|
||||
|
||||
> **상위 문서**: [백엔드 가이드 인덱스](./index.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 모든 라우트는 name() 필수: ->name('api.users.index')
|
||||
2. 접두사: api.*, web.*, vendor-module.*
|
||||
3. URL: /api/admin/*, /api/auth/*, /api/public/*
|
||||
4. 권한: permission: 또는 Middleware에서 체크
|
||||
5. REST 패턴: index, store, show, update, destroy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [라우트 이름 규칙](#라우트-이름-규칙)
|
||||
2. [URL 경로 규칙](#url-경로-규칙)
|
||||
3. [권한 체크](#권한-체크)
|
||||
4. [라우트 정의 예시](#라우트-정의-예시)
|
||||
5. [개발 체크리스트](#개발-체크리스트)
|
||||
|
||||
---
|
||||
|
||||
## 라우트 이름 규칙
|
||||
|
||||
### 필수 원칙
|
||||
|
||||
- **모든 라우트는 `name` 필수**
|
||||
- 일관된 네이밍 컨벤션 준수
|
||||
|
||||
### 접두사 규칙
|
||||
|
||||
| 타입 | 접두사 | 예시 |
|
||||
|------|--------|------|
|
||||
| API | `api.` | `api.users.index` |
|
||||
| WEB | `web.` | `web.dashboard` |
|
||||
| 모듈 | `[vendor-module].` | `sirsoft-ecommerce.products.index` |
|
||||
| 플러그인 | `[vendor-plugin].` | `sirsoft-payment.settings` |
|
||||
|
||||
### 조합 규칙
|
||||
|
||||
```php
|
||||
// 코어 API
|
||||
->name('api.users.index')
|
||||
->name('api.users.store')
|
||||
|
||||
// 모듈 API
|
||||
->name('api.sirsoft-ecommerce.products.index')
|
||||
->name('api.sirsoft-ecommerce.products.store')
|
||||
|
||||
// 플러그인 API
|
||||
->name('api.sirsoft-payment.transactions.index')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## URL 경로 규칙
|
||||
|
||||
### 경로 패턴
|
||||
|
||||
| 타입 | 패턴 | 예시 |
|
||||
|------|------|------|
|
||||
| 코어 | `/admin/[기능명]` | `/admin/users` |
|
||||
| 모듈 | `/admin/[vendor-module]/[기능명]` | `/admin/sirsoft-ecommerce/products` |
|
||||
| 플러그인 | `/admin/[vendor-plugin]/[기능명]` | `/admin/sirsoft-payment/settings` |
|
||||
| 공개 API | `/api/[vendor-module]/[기능명]` | `/api/sirsoft-ecommerce/products` |
|
||||
|
||||
### 리소스 URL 규칙
|
||||
|
||||
```text
|
||||
# 목록 조회
|
||||
GET /admin/sirsoft-ecommerce/products
|
||||
|
||||
# 단일 조회
|
||||
GET /admin/sirsoft-ecommerce/products/{id}
|
||||
|
||||
# 생성
|
||||
POST /admin/sirsoft-ecommerce/products
|
||||
|
||||
# 수정
|
||||
PUT /admin/sirsoft-ecommerce/products/{id}
|
||||
|
||||
# 삭제
|
||||
DELETE /admin/sirsoft-ecommerce/products/{id}
|
||||
```
|
||||
|
||||
### 라이선스 API 라우트
|
||||
|
||||
코어 및 확장의 LICENSE 파일 내용을 반환하는 API 엔드포인트입니다.
|
||||
|
||||
```text
|
||||
GET /api/admin/license # 코어 LICENSE 반환
|
||||
GET /api/admin/modules/{identifier}/license # 모듈 LICENSE 반환
|
||||
GET /api/admin/plugins/{identifier}/license # 플러그인 LICENSE 반환
|
||||
GET /api/admin/templates/{identifier}/license # 템플릿 LICENSE 반환
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 권한 체크
|
||||
|
||||
### 권한 체크 방식
|
||||
|
||||
```text
|
||||
주의: FormRequest의 authorize() 메서드 사용 금지
|
||||
필수: 라우트에 permission 미들웨어 체인
|
||||
```
|
||||
|
||||
### 권한 미들웨어 사용
|
||||
|
||||
```php
|
||||
// ✅ DO: 라우트에 permission 미들웨어 사용
|
||||
Route::get('/products', [ProductController::class, 'index'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.view')
|
||||
->name('api.sirsoft-ecommerce.products.index');
|
||||
|
||||
// ❌ DON'T: FormRequest에서 권한 체크
|
||||
class ProductRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
// 이 방식 사용 금지
|
||||
return $this->user()->can('view-products');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 권한 네이밍 규칙
|
||||
|
||||
```text
|
||||
[vendor-module].[resource].[action]
|
||||
|
||||
예시:
|
||||
sirsoft-ecommerce.products.view
|
||||
sirsoft-ecommerce.products.create
|
||||
sirsoft-ecommerce.products.edit
|
||||
sirsoft-ecommerce.products.delete
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 라우트 정의 예시
|
||||
|
||||
### 모듈 라우트 파일
|
||||
|
||||
```php
|
||||
// modules/sirsoft-ecommerce/src/routes/api.php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Sirsoft\Ecommerce\Controllers\Api\Admin\ProductController;
|
||||
|
||||
Route::prefix('admin/sirsoft-ecommerce')->middleware(['auth:sanctum', 'admin'])->group(function () {
|
||||
// 상품 관리 (권한 체크 포함)
|
||||
Route::get('/products', [ProductController::class, 'index'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.view')
|
||||
->name('api.sirsoft-ecommerce.products.index');
|
||||
|
||||
Route::post('/products', [ProductController::class, 'store'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.create')
|
||||
->name('api.sirsoft-ecommerce.products.store');
|
||||
|
||||
Route::get('/products/{id}', [ProductController::class, 'show'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.view')
|
||||
->name('api.sirsoft-ecommerce.products.show');
|
||||
|
||||
Route::put('/products/{id}', [ProductController::class, 'update'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.edit')
|
||||
->name('api.sirsoft-ecommerce.products.update');
|
||||
|
||||
Route::delete('/products/{id}', [ProductController::class, 'destroy'])
|
||||
->middleware('permission:sirsoft-ecommerce.products.delete')
|
||||
->name('api.sirsoft-ecommerce.products.destroy');
|
||||
});
|
||||
```
|
||||
|
||||
### 코어 라우트 파일
|
||||
|
||||
```php
|
||||
// routes/api.php
|
||||
|
||||
use App\Http\Controllers\Api\Admin\UserController;
|
||||
|
||||
Route::prefix('admin')->middleware(['auth:sanctum', 'admin'])->group(function () {
|
||||
// 사용자 관리
|
||||
Route::get('/users', [UserController::class, 'index'])
|
||||
->middleware('permission:users.view')
|
||||
->name('api.users.index');
|
||||
|
||||
Route::post('/users', [UserController::class, 'store'])
|
||||
->middleware('permission:users.create')
|
||||
->name('api.users.store');
|
||||
});
|
||||
```
|
||||
|
||||
### 권한 바이패스 라우트 (except 옵션)
|
||||
|
||||
자기 자신 또는 소유자에 대해 권한 체크를 바이패스하는 라우트:
|
||||
|
||||
```php
|
||||
// routes/api.php
|
||||
|
||||
Route::prefix('admin')->middleware(['auth:sanctum', 'admin'])->group(function () {
|
||||
// 사용자 수정: 자기 자신은 core.users.update 권한 없이 수정 가능
|
||||
Route::put('/users/{user}', [UserController::class, 'update'])
|
||||
->middleware('permission:admin,core.users.update,except:self:user')
|
||||
->name('api.admin.users.update');
|
||||
|
||||
// 메뉴 수정: 소유자는 core.menus.update 권한 없이 수정 가능 (향후 적용 예시)
|
||||
Route::put('/menus/{menu}', [MenuController::class, 'update'])
|
||||
->middleware('permission:admin,core.menus.update,except:owner:menu')
|
||||
->name('api.admin.menus.update');
|
||||
});
|
||||
```
|
||||
|
||||
> 상세 문법: [middleware.md](middleware.md) "permission 미들웨어 except 옵션" 참조
|
||||
|
||||
### 공개 API 라우트
|
||||
|
||||
```php
|
||||
// modules/sirsoft-ecommerce/src/routes/api.php
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Controllers\Api\Public\ProductController;
|
||||
|
||||
Route::prefix('api/sirsoft-ecommerce')->group(function () {
|
||||
// 공개 상품 API (인증 불필요)
|
||||
Route::get('/products', [ProductController::class, 'index'])
|
||||
->name('api.sirsoft-ecommerce.public.products.index');
|
||||
|
||||
Route::get('/products/{id}', [ProductController::class, 'show'])
|
||||
->name('api.sirsoft-ecommerce.public.products.show');
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 개발 체크리스트
|
||||
|
||||
### 라우트 정의 시 확인사항
|
||||
|
||||
- [ ] 라우트에 `name()` 메서드로 이름 지정
|
||||
- [ ] 적절한 접두사 사용 (api., web., vendor-module.)
|
||||
- [ ] URL 경로 규칙 준수 (/admin/[vendor-module]/[기능명])
|
||||
- [ ] 권한이 필요한 라우트에 `permission` 미들웨어 적용
|
||||
- [ ] 인증이 필요한 라우트에 `auth:sanctum` 미들웨어 적용
|
||||
- [ ] 관리자 라우트에 `admin` 미들웨어 적용
|
||||
- [ ] FormRequest의 `authorize()` 메서드에서 권한 체크하지 않음
|
||||
|
||||
### 라우트 테스트 확인사항
|
||||
|
||||
- [ ] 인증 없이 접근 시 401 반환
|
||||
- [ ] 권한 없이 접근 시 403 반환
|
||||
- [ ] 올바른 권한으로 접근 시 성공
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [컨트롤러 계층 구조](./controllers.md) - 컨트롤러 네이밍 규칙
|
||||
- [미들웨어 등록 규칙](./middleware.md) - 미들웨어 실행 순서
|
||||
- [검증 로직 구현](./validation.md) - FormRequest 사용 규칙
|
||||
|
||||
### SEO 라우트
|
||||
|
||||
| URL | 메서드 | 라우트명 | 컨트롤러 | 비고 |
|
||||
|-----|--------|---------|---------|------|
|
||||
| /sitemap.xml | GET | web.sitemap | SitemapController@index | catch-all보다 위에 정의 |
|
||||
| /api/admin/seo/stats | GET | api.admin.seo.stats | SeoCacheController | 관리자 전용 |
|
||||
| /api/admin/seo/clear-cache | POST | api.admin.seo.clear-cache | SeoCacheController | 관리자 전용 |
|
||||
| /api/admin/seo/warmup | POST | api.admin.seo.warmup | SeoCacheController | 관리자 전용 |
|
||||
| /api/admin/seo/cached-urls | GET | api.admin.seo.cached-urls | SeoCacheController | 관리자 전용 |
|
||||
|
||||
> 상세: [seo-system.md](seo-system.md)
|
||||
@@ -0,0 +1,370 @@
|
||||
# Scout 검색 엔진 시스템 (Search System)
|
||||
|
||||
> **중요도**: 높음
|
||||
> **관련 문서**: [service-repository.md](service-repository.md) | [hooks.md](../extension/hooks.md) | [database-guide.md](../database-guide.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. Laravel Scout + DatabaseFulltextEngine: MySQL FULLTEXT + ngram 기반 검색 (기본 드라이버)
|
||||
2. FulltextSearchable 인터페이스: searchableColumns() + searchableWeights() 구현 필수
|
||||
3. LIKE fallback 자동 적용: FULLTEXT 미지원 DBMS(SQLite, PostgreSQL)에서 자동 전환
|
||||
4. 확장 포인트: core.search.engine_drivers 필터 훅으로 Meilisearch 등 커스텀 엔진 등록 가능
|
||||
5. AsUnicodeJson 캐스트: JSON 컬럼 FULLTEXT 검색 시 한글 \uXXXX 이스케이프 방지 필수
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [아키텍처 개요](#아키텍처-개요)
|
||||
2. [FulltextSearchable 인터페이스](#fulltextsearchable-인터페이스)
|
||||
3. [검색 엔진 드라이버](#검색-엔진-드라이버)
|
||||
4. [확장 포인트](#확장-포인트)
|
||||
5. [마이그레이션](#마이그레이션)
|
||||
6. [AsUnicodeJson 캐스트](#asunicodejson-캐스트)
|
||||
7. [환경설정](#환경설정)
|
||||
8. [관련 문서](#관련-문서)
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 개요
|
||||
|
||||
G7은 **Laravel Scout**를 통해 검색 기능을 제공하며, 기본 검색 엔진으로 **DatabaseFulltextEngine**을 사용합니다.
|
||||
|
||||
**핵심 구조**:
|
||||
|
||||
```
|
||||
Controller/Service
|
||||
↓ Model::search($keyword)
|
||||
Laravel Scout (EngineManager)
|
||||
↓ SCOUT_DRIVER 기반 엔진 선택
|
||||
DatabaseFulltextEngine
|
||||
↓ FulltextSearchable 인터페이스 참조
|
||||
├── MySQL/MariaDB → MATCH...AGAINST IN BOOLEAN MODE
|
||||
└── SQLite/PostgreSQL → LIKE fallback
|
||||
```
|
||||
|
||||
**핵심 컴포넌트**:
|
||||
|
||||
| 파일 | 역할 |
|
||||
|------|------|
|
||||
| `app/Search/Contracts/FulltextSearchable.php` | 검색 대상 컬럼/가중치 정의 인터페이스 |
|
||||
| `app/Search/Engines/DatabaseFulltextEngine.php` | MySQL FULLTEXT + ngram Scout 엔진 |
|
||||
| `app/Providers/ScoutServiceProvider.php` | 엔진 등록 + 필터 훅 처리 |
|
||||
| `app/Casts/AsUnicodeJson.php` | FULLTEXT ngram용 UTF-8 JSON 캐스트 |
|
||||
| `config/scout.php` | Scout 설정 (드라이버, 큐, 소프트삭제 등) |
|
||||
|
||||
**설계 원칙**:
|
||||
|
||||
- MySQL 테이블 자체가 인덱스 소스 -- 외부 검색 서버 불필요
|
||||
- `update()`, `delete()`, `flush()`, `createIndex()`, `deleteIndex()`는 모두 **no-op** (MySQL이 자동 관리)
|
||||
- FULLTEXT 미지원 DBMS에서 LIKE fallback 자동 적용 (테스트 환경 SQLite 호환)
|
||||
|
||||
---
|
||||
|
||||
## FulltextSearchable 인터페이스
|
||||
|
||||
`App\Search\Contracts\FulltextSearchable` 인터페이스를 구현한 모델만 DatabaseFulltextEngine에서 검색됩니다.
|
||||
|
||||
### 필수 메서드
|
||||
|
||||
| 메서드 | 반환 타입 | 설명 |
|
||||
|--------|----------|------|
|
||||
| `searchableColumns()` | `array<string>` | FULLTEXT 검색 대상 컬럼명 배열 |
|
||||
| `searchableWeights()` | `array<string, float>` | 컬럼별 검색 가중치 (높을수록 상위 노출) |
|
||||
|
||||
### 구현 예시 (Product 모델)
|
||||
|
||||
```php
|
||||
use App\Search\Contracts\FulltextSearchable;
|
||||
use Laravel\Scout\Searchable;
|
||||
|
||||
class Product extends Model implements FulltextSearchable
|
||||
{
|
||||
use Searchable;
|
||||
|
||||
// FULLTEXT 검색 대상 컬럼
|
||||
public function searchableColumns(): array
|
||||
{
|
||||
return ['name', 'description'];
|
||||
}
|
||||
|
||||
// 컬럼별 가중치 (name 매칭이 description보다 2배 높은 점수)
|
||||
public function searchableWeights(): array
|
||||
{
|
||||
return [
|
||||
'name' => 2.0,
|
||||
'description' => 1.0,
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 가중치 기반 스코어 계산
|
||||
|
||||
검색 결과는 `_ft_score` 가상 컬럼으로 관련성 점수가 부여됩니다:
|
||||
|
||||
```sql
|
||||
-- MySQL에서 생성되는 쿼리 (예시)
|
||||
SELECT products.*,
|
||||
(MATCH(`name`) AGAINST(? IN BOOLEAN MODE) * 2.0
|
||||
+ MATCH(`description`) AGAINST(? IN BOOLEAN MODE) * 1.0) as _ft_score
|
||||
FROM products
|
||||
WHERE (MATCH(`name`) AGAINST(? IN BOOLEAN MODE)
|
||||
OR MATCH(`description`) AGAINST(? IN BOOLEAN MODE))
|
||||
ORDER BY _ft_score DESC
|
||||
```
|
||||
|
||||
LIKE fallback 시 `_ft_score`는 항상 0 (관련성 순위 불가).
|
||||
|
||||
### 현재 FulltextSearchable 구현 모델
|
||||
|
||||
| 모듈 | 모델 | 검색 컬럼 |
|
||||
|------|------|----------|
|
||||
| sirsoft-ecommerce | Product | name, description |
|
||||
| sirsoft-ecommerce | Category | name |
|
||||
| sirsoft-ecommerce | Brand | name |
|
||||
| sirsoft-ecommerce | Coupon | name |
|
||||
| sirsoft-ecommerce | ProductCommonInfo | name |
|
||||
| sirsoft-board | Post | (모델 참조) |
|
||||
| sirsoft-page | Page | (모델 참조) |
|
||||
|
||||
---
|
||||
|
||||
## 검색 엔진 드라이버
|
||||
|
||||
### 기본 드라이버: mysql-fulltext
|
||||
|
||||
`DatabaseFulltextEngine`은 MySQL FULLTEXT + ngram 파서를 활용합니다:
|
||||
|
||||
- **MySQL 8.0+**: `MATCH...AGAINST IN BOOLEAN MODE` + **ngram 파서** (한글 2글자 토큰 분리)
|
||||
- **MariaDB**: `MATCH...AGAINST IN BOOLEAN MODE` + 기본 파서 (ngram 미지원)
|
||||
- **SQLite/PostgreSQL**: `LIKE %keyword%` fallback (개발/테스트 환경 호환)
|
||||
|
||||
### DBMS 지원 판단
|
||||
|
||||
```php
|
||||
// FULLTEXT 지원 여부 (MySQL, MariaDB만 true)
|
||||
DatabaseFulltextEngine::supportsFulltext();
|
||||
|
||||
// ngram 파서 지원 여부 (MySQL만 true, MariaDB는 false)
|
||||
DatabaseFulltextEngine::supportsNgramParser();
|
||||
```
|
||||
|
||||
### SCOUT_DRIVER 전환
|
||||
|
||||
`.env`에서 드라이버를 변경하면 즉시 적용됩니다:
|
||||
|
||||
```env
|
||||
# 기본값: MySQL FULLTEXT
|
||||
SCOUT_DRIVER=mysql-fulltext
|
||||
|
||||
# 플러그인에서 등록한 드라이버로 전환
|
||||
SCOUT_DRIVER=meilisearch
|
||||
```
|
||||
|
||||
### whereFulltext() 정적 헬퍼
|
||||
|
||||
Scout Builder를 사용할 수 없는 곳 (관계 검색, 서브쿼리 등)에서 FULLTEXT 조건을 직접 추가합니다:
|
||||
|
||||
```php
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
|
||||
// Repository에서 사용 예시
|
||||
$query = Post::query();
|
||||
DatabaseFulltextEngine::whereFulltext($query, 'content', $keyword);
|
||||
DatabaseFulltextEngine::whereFulltext($query, 'title', $keyword, 'or');
|
||||
```
|
||||
|
||||
DBMS에 따라 자동 분기:
|
||||
- MySQL/MariaDB: `WHERE MATCH(\`content\`) AGAINST(? IN BOOLEAN MODE)`
|
||||
- 그 외: `WHERE content LIKE '%keyword%'`
|
||||
|
||||
---
|
||||
|
||||
## 확장 포인트
|
||||
|
||||
### core.search.engine_drivers 필터 훅
|
||||
|
||||
`ScoutServiceProvider`에서 `core.search.engine_drivers` 필터 훅을 통해 플러그인이 추가 검색 엔진을 등록할 수 있습니다.
|
||||
|
||||
```php
|
||||
// 플러그인 ServiceProvider에서 등록
|
||||
use App\Extension\HookManager;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
HookManager::addFilter('core.search.engine_drivers', function (array $drivers) {
|
||||
$drivers['meilisearch'] = \App\Search\Engines\MeilisearchEngine::class;
|
||||
return $drivers;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
등록 후 `.env`에서 `SCOUT_DRIVER=meilisearch`로 전환하면 해당 엔진이 사용됩니다.
|
||||
|
||||
### ScoutServiceProvider 동작 흐름
|
||||
|
||||
```php
|
||||
// app/Providers/ScoutServiceProvider.php
|
||||
|
||||
// 1. 기본 드라이버 맵
|
||||
$drivers = ['mysql-fulltext' => DatabaseFulltextEngine::class];
|
||||
|
||||
// 2. 필터 훅으로 플러그인 드라이버 수집
|
||||
$drivers = HookManager::applyFilters('core.search.engine_drivers', $drivers);
|
||||
|
||||
// 3. EngineManager에 모든 드라이버 등록
|
||||
$this->app->resolving(EngineManager::class, function (EngineManager $manager) use ($drivers) {
|
||||
foreach ($drivers as $name => $engineClass) {
|
||||
$manager->extend($name, fn () => $this->app->make($engineClass));
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 마이그레이션
|
||||
|
||||
### addFulltextIndex() 헬퍼
|
||||
|
||||
`DatabaseFulltextEngine::addFulltextIndex()`는 DBMS별 조건부 DDL을 처리합니다:
|
||||
|
||||
```php
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
|
||||
// 마이그레이션 up()에서 사용
|
||||
public function up(): void
|
||||
{
|
||||
DatabaseFulltextEngine::addFulltextIndex(
|
||||
'ecommerce_products', // 테이블명 (prefix 제외)
|
||||
'ft_ecommerce_products_name', // 인덱스명
|
||||
'name' // 대상 컬럼 (string 또는 array)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**DBMS별 동작**:
|
||||
|
||||
| DBMS | 생성되는 DDL |
|
||||
|------|-------------|
|
||||
| MySQL 8.0+ | `ALTER TABLE ... ADD FULLTEXT INDEX ... WITH PARSER ngram` |
|
||||
| MariaDB | `ALTER TABLE ... ADD FULLTEXT INDEX ...` (ngram 없음) |
|
||||
| SQLite/PostgreSQL | 스킵 (no-op) |
|
||||
|
||||
### 마이그레이션 down() 패턴
|
||||
|
||||
```php
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('ecommerce_products')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$indexes = array_column(Schema::getIndexes('ecommerce_products'), 'name');
|
||||
|
||||
Schema::table('ecommerce_products', function (Blueprint $table) use ($indexes) {
|
||||
if (in_array('ft_ecommerce_products_name', $indexes)) {
|
||||
$table->dropIndex('ft_ecommerce_products_name');
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 인덱스 네이밍 규칙
|
||||
|
||||
```
|
||||
ft_{테이블명}_{컬럼명}
|
||||
```
|
||||
|
||||
예: `ft_ecommerce_products_name`, `ft_ecommerce_products_description`
|
||||
|
||||
### 복합 컬럼 인덱스
|
||||
|
||||
```php
|
||||
// 여러 컬럼을 하나의 FULLTEXT 인덱스로 생성
|
||||
DatabaseFulltextEngine::addFulltextIndex(
|
||||
'posts',
|
||||
'ft_posts_title_content',
|
||||
['title', 'content'] // 배열 전달
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## AsUnicodeJson 캐스트
|
||||
|
||||
### 문제
|
||||
|
||||
Laravel 기본 `array` 캐스트는 `json_encode()`로 한글을 `\uXXXX`로 이스케이프합니다:
|
||||
|
||||
```json
|
||||
// 기본 array 캐스트: \uXXXX 이스케이프
|
||||
{"ko": "\uc0c1\ud488\uba85"}
|
||||
|
||||
// AsUnicodeJson 캐스트: 실제 UTF-8
|
||||
{"ko": "상품명"}
|
||||
```
|
||||
|
||||
MySQL ngram 토크나이저는 **실제 UTF-8 문자**를 기준으로 토큰을 생성하므로, `\uXXXX` 이스케이프된 데이터에서는 한글 검색이 동작하지 않습니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```php
|
||||
use App\Casts\AsUnicodeJson;
|
||||
|
||||
class Product extends Model
|
||||
{
|
||||
protected $casts = [
|
||||
'name' => AsUnicodeJson::class, // FULLTEXT 검색 대상 JSON 컬럼
|
||||
'description' => AsUnicodeJson::class, // FULLTEXT 검색 대상 JSON 컬럼
|
||||
'meta_keywords' => 'array', // 검색 대상 아닌 컬럼은 기본 캐스트 사용 가능
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### 적용 대상
|
||||
|
||||
FULLTEXT 인덱스가 걸리는 JSON 타입 컬럼에는 반드시 `AsUnicodeJson` 캐스트를 사용합니다. 내부적으로 `JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES` 플래그를 사용합니다.
|
||||
|
||||
---
|
||||
|
||||
## 환경설정
|
||||
|
||||
### config/scout.php 주요 설정
|
||||
|
||||
| 키 | 기본값 | 설명 |
|
||||
|----|--------|------|
|
||||
| `driver` | `mysql-fulltext` | 검색 엔진 드라이버 (`SCOUT_DRIVER` 환경변수) |
|
||||
| `prefix` | `''` | 인덱스 접두사 |
|
||||
| `queue` | `false` | 인덱스 동기화 큐 사용 여부 |
|
||||
| `soft_delete` | `true` | 소프트 삭제 레코드 필터링 |
|
||||
| `after_commit` | `false` | DB 트랜잭션 커밋 후 인덱스 동기화 |
|
||||
| `chunk.searchable` | `500` | 대량 인덱싱 시 청크 크기 |
|
||||
|
||||
### .env 설정
|
||||
|
||||
```env
|
||||
# 검색 엔진 드라이버 (기본: mysql-fulltext)
|
||||
SCOUT_DRIVER=mysql-fulltext
|
||||
|
||||
# 인덱스 접두사 (선택)
|
||||
SCOUT_PREFIX=
|
||||
|
||||
# 인덱스 동기화 큐 사용 (선택)
|
||||
SCOUT_QUEUE=false
|
||||
```
|
||||
|
||||
> **참고**: `mysql-fulltext` 드라이버는 MySQL 테이블 자체가 인덱스이므로 `SCOUT_QUEUE`, `SCOUT_PREFIX`는 실질적으로 사용되지 않습니다. 외부 검색 엔진(Meilisearch 등)으로 전환 시 의미가 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [Service-Repository 패턴](service-repository.md) - Repository에서 whereFulltext() 사용
|
||||
- [훅 시스템](../extension/hooks.md) - core.search.engine_drivers 필터 훅
|
||||
- [데이터베이스 가이드](../database-guide.md) - 마이그레이션 규칙
|
||||
- [플러그인 개발](../extension/plugin-development.md) - 검색 엔진 플러그인 개발
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,305 @@
|
||||
# 서비스 프로바이더 안전성
|
||||
|
||||
> **목차**: [index.md](./index.md) | [enum.md](./enum.md) | [controllers.md](./controllers.md) | [service-repository.md](./service-repository.md) | [validation.md](./validation.md) | [exceptions.md](./exceptions.md) | [api-resources.md](./api-resources.md) | [routing.md](./routing.md) | [response-helper.md](./response-helper.md) | [middleware.md](./middleware.md) | [authentication.md](./authentication.md) | **service-provider.md**
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. DB 접근 전 .env 파일 존재 확인 필수
|
||||
2. 테이블 존재 여부 Schema::hasTable() 체크
|
||||
3. 인스톨러 안정성: 마이그레이션 전에도 부팅 가능해야 함
|
||||
4. 조건 미충족 시 예외 대신 안전하게 스킵
|
||||
5. runningInConsole() + 'migrate' 명령 감지로 스킵
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
1. [핵심 원칙](#핵심-원칙)
|
||||
2. [검증이 필요한 경우](#검증이-필요한-경우)
|
||||
3. [검증 체크리스트](#검증-체크리스트)
|
||||
4. [잘못된 예시](#잘못된-예시)
|
||||
5. [올바른 예시](#올바른-예시)
|
||||
6. [실행 흐름 다이어그램](#실행-흐름-다이어그램)
|
||||
7. [다른 서비스 프로바이더 적용 예시](#다른-서비스-프로바이더-적용-예시)
|
||||
8. [서비스 프로바이더 개발 체크리스트](#서비스-프로바이더-개발-체크리스트)
|
||||
9. [인스톨러 테스트 시나리오](#인스톨러-테스트-시나리오)
|
||||
|
||||
---
|
||||
|
||||
## 핵심 원칙
|
||||
|
||||
```text
|
||||
필수: 서비스 프로바이더에서 DB 접근 전 .env + 테이블 존재 확인
|
||||
필수: .env 파일 및 테이블 존재 여부 확인 후 접근
|
||||
```
|
||||
|
||||
**핵심 원칙**:
|
||||
|
||||
- **인스톨러 안정성**: `.env` 파일이 없는 상태에서도 `composer install` 실행 가능해야 함
|
||||
- **단계적 초기화**: DB 테이블이 없는 상태(마이그레이션 전)에서도 애플리케이션 부팅 가능해야 함
|
||||
- **안전한 스킵**: 조건 미충족 시 예외 발생 대신 안전하게 건너뛰기
|
||||
|
||||
---
|
||||
|
||||
## 검증이 필요한 경우
|
||||
|
||||
| 상황 | 검증 항목 | 필요 이유 |
|
||||
|------|----------|----------|
|
||||
| DB 쿼리 실행 | `.env` 파일, 테이블 존재 | 인스톨러 실행 전 오류 방지 |
|
||||
| 모듈/플러그인 로드 | 관련 테이블 존재 | 마이그레이션 전 오류 방지 |
|
||||
| 설정값 로드 | `.env` 파일 존재 | 초기 설정 전 오류 방지 |
|
||||
|
||||
---
|
||||
|
||||
## 검증 체크리스트
|
||||
|
||||
1. **`.env` 파일 존재 여부**: `File::exists(base_path('.env'))`
|
||||
2. **필수 테이블 존재 여부**: `Schema::hasTable('table_name')`
|
||||
3. **조건 미충족 시 안전하게 return**
|
||||
|
||||
---
|
||||
|
||||
## 잘못된 예시
|
||||
|
||||
```php
|
||||
// ❌ 검증 없이 DB 접근 - 인스톨러 실행 시 오류 발생
|
||||
class ModuleRouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function boot(): void
|
||||
{
|
||||
$this->routes(function () {
|
||||
$this->loadModuleRoutes();
|
||||
});
|
||||
}
|
||||
|
||||
protected function loadModuleRoutes(): void
|
||||
{
|
||||
$modulesPath = base_path('modules');
|
||||
|
||||
if (! File::exists($modulesPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ❌ .env 파일이나 테이블 확인 없이 DB 쿼리 실행
|
||||
$activeModules = Module::where('status', 'active')->get();
|
||||
|
||||
foreach ($activeModules as $module) {
|
||||
// 라우트 로드...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**오류 시나리오**:
|
||||
|
||||
```bash
|
||||
# 인스톨러 실행 중
|
||||
composer install
|
||||
↓
|
||||
package:discover 자동 실행
|
||||
↓
|
||||
ModuleRouteServiceProvider 로드
|
||||
↓
|
||||
Module::where() 실행 시도
|
||||
↓
|
||||
❌ SQLSTATE[HY000] [1045] Access denied (using password: NO)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 올바른 예시
|
||||
|
||||
### 1. .env 파일 체크 추가
|
||||
|
||||
```php
|
||||
// ✅ .env 파일 및 테이블 존재 확인
|
||||
class ModuleRouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function boot(): void
|
||||
{
|
||||
$this->routes(function () {
|
||||
$this->loadModuleRoutes();
|
||||
});
|
||||
}
|
||||
|
||||
protected function loadModuleRoutes(): void
|
||||
{
|
||||
// ✅ .env 파일이 없으면 스킵 (인스톨러 실행 전)
|
||||
if (! File::exists(base_path('.env'))) {
|
||||
return;
|
||||
}
|
||||
|
||||
$modulesPath = base_path('modules');
|
||||
|
||||
if (! File::exists($modulesPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ✅ 데이터베이스 테이블이 존재하지 않으면 스킵 (마이그레이션 전)
|
||||
if (! Schema::hasTable('modules')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 안전하게 DB 접근
|
||||
$activeModules = Module::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray();
|
||||
|
||||
foreach ($activeModules as $moduleIdentifier) {
|
||||
// 라우트 로드...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Service 클래스에서의 적용
|
||||
|
||||
```php
|
||||
class TemplateService
|
||||
{
|
||||
/**
|
||||
* 활성화된 모듈의 routes 데이터 로드
|
||||
*/
|
||||
private function loadActiveModulesRoutesData(): array
|
||||
{
|
||||
// ✅ .env 파일이 없으면 빈 배열 반환 (인스톨러 실행 전)
|
||||
if (! file_exists(base_path('.env'))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// ✅ modules 테이블이 없으면 빈 배열 반환 (마이그레이션 전)
|
||||
if (! Schema::hasTable('modules')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 안전하게 모듈 데이터 로드
|
||||
$routes = [];
|
||||
$activeModules = $this->moduleManager->getActiveModules();
|
||||
|
||||
foreach ($activeModules as $module) {
|
||||
// routes.json 로드...
|
||||
}
|
||||
|
||||
return $routes;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 실행 흐름 다이어그램
|
||||
|
||||
```
|
||||
인스톨러 단계 1: composer install
|
||||
├─ .env 없음 → ModuleRouteServiceProvider 스킵 ✅
|
||||
└─ package:discover 정상 완료
|
||||
|
||||
인스톨러 단계 2: .env 생성
|
||||
├─ DB 연결 정보 입력
|
||||
└─ .env 파일 생성 완료
|
||||
|
||||
인스톨러 단계 3: 마이그레이션
|
||||
├─ modules 테이블 없음 → ModuleRouteServiceProvider 스킵 ✅
|
||||
└─ 테이블 생성 완료
|
||||
|
||||
설치 완료 후:
|
||||
├─ .env 있음 ✅
|
||||
├─ modules 테이블 있음 ✅
|
||||
└─ ModuleRouteServiceProvider 정상 실행 ✅
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 다른 서비스 프로바이더 적용 예시
|
||||
|
||||
### PluginRouteServiceProvider
|
||||
|
||||
```php
|
||||
class PluginRouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
protected function loadPluginRoutes(): void
|
||||
{
|
||||
// ✅ 동일한 패턴 적용
|
||||
if (! File::exists(base_path('.env'))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasTable('plugins')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 플러그인 라우트 로드...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### ConfigServiceProvider
|
||||
|
||||
```php
|
||||
class ConfigServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function boot(): void
|
||||
{
|
||||
// ✅ 동일한 패턴 적용
|
||||
if (! File::exists(base_path('.env'))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasTable('settings')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 동적 설정 로드...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 서비스 프로바이더 개발 체크리스트
|
||||
|
||||
- [ ] DB 접근이 필요한 경우 `.env` 파일 존재 확인
|
||||
- [ ] 특정 테이블 접근 시 `Schema::hasTable()` 확인
|
||||
- [ ] 조건 미충족 시 예외 발생 대신 `return`으로 안전하게 스킵
|
||||
- [ ] 인스톨러 환경에서 테스트 수행
|
||||
- [ ] `composer install` 단독 실행 테스트
|
||||
|
||||
---
|
||||
|
||||
## 인스톨러 테스트 시나리오
|
||||
|
||||
```bash
|
||||
# 1. .env 없이 composer install
|
||||
rm .env
|
||||
composer install
|
||||
# 예상: 정상 완료 (오류 없음)
|
||||
|
||||
# 2. .env 생성 후 애플리케이션 부팅
|
||||
cp .env.example .env
|
||||
php artisan config:clear
|
||||
# 예상: 정상 부팅 (modules 테이블 없어도 오류 없음)
|
||||
|
||||
# 3. 마이그레이션 후 정상 동작
|
||||
php artisan migrate
|
||||
# 예상: 모든 기능 정상 동작
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 관련 이슈
|
||||
|
||||
- 인스톨러에서 `composer install` 시 DB 접근 오류
|
||||
- 마이그레이션 전 애플리케이션 부팅 실패
|
||||
- CI/CD 파이프라인에서 의존성 설치 오류
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [middleware.md](./middleware.md) - 미들웨어 등록 규칙
|
||||
- [authentication.md](./authentication.md) - 인증 및 세션 처리
|
||||
- [index.md](./index.md) - 백엔드 가이드 인덱스
|
||||
@@ -0,0 +1,972 @@
|
||||
# Service-Repository 패턴
|
||||
|
||||
> **백엔드 가이드** | [목차로 돌아가기](index.md)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. RepositoryInterface 주입 필수 (구체 클래스 직접 주입 금지)
|
||||
2. CoreServiceProvider에서 Interface-구현체 바인딩
|
||||
3. Service에서 훅 실행: before_create → applyFilters → create → after_create
|
||||
4. 검증 로직은 FormRequest에서 (Service에 검증 금지)
|
||||
5. 다중 검색은 HasMultipleSearchFilters Trait 사용
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 목차
|
||||
|
||||
- [개요](#개요)
|
||||
- [Repository 인터페이스](#repository-인터페이스)
|
||||
- [Service 클래스](#service-클래스)
|
||||
- [트랜잭션 및 관계 삭제 패턴](#트랜잭션-및-관계-삭제-패턴)
|
||||
- [상태 변경 자동 처리](#상태-변경-자동-처리)
|
||||
- [Repository 클래스](#repository-클래스)
|
||||
- [다중 검색 필터 Trait](#다중-검색-필터-trait-hasmultiplesearchfilters)
|
||||
- [모듈에서 Repository 인터페이스 바인딩](#모듈에서-repository-인터페이스-바인딩)
|
||||
- [관련 문서](#관련-문서)
|
||||
|
||||
---
|
||||
|
||||
## 개요
|
||||
|
||||
Service-Repository 패턴은 비즈니스 로직과 데이터 액세스 로직을 분리하는 아키텍처 패턴입니다.
|
||||
|
||||
```
|
||||
Controller → Request → Service → RepositoryInterface → Repository → Model
|
||||
```
|
||||
|
||||
| 계층 | 역할 |
|
||||
|------|------|
|
||||
| **Service** | 비즈니스 로직, 훅 실행, 트랜잭션 관리 |
|
||||
| **RepositoryInterface** | Repository 추상화 계약 정의 |
|
||||
| **Repository** | 데이터 액세스 구현, 쿼리 로직 캡슐화 |
|
||||
|
||||
---
|
||||
|
||||
## Repository 인터페이스
|
||||
|
||||
### 핵심 원칙
|
||||
|
||||
```
|
||||
필수: Repository 인터페이스를 통한 DI (구체 클래스 직접 타입힌트 금지)
|
||||
필수: Repository 인터페이스를 통한 DI
|
||||
✅ 필수: CoreServiceProvider에서 인터페이스-구현체 바인딩
|
||||
```
|
||||
|
||||
### 인터페이스 위치
|
||||
|
||||
```
|
||||
app/Contracts/Repositories/
|
||||
├── LayoutRepositoryInterface.php
|
||||
├── ModuleRepositoryInterface.php
|
||||
├── MenuRepositoryInterface.php
|
||||
├── RoleRepositoryInterface.php
|
||||
├── TemplateRepositoryInterface.php
|
||||
├── PluginRepositoryInterface.php
|
||||
├── UserRepositoryInterface.php
|
||||
├── PermissionRepositoryInterface.php
|
||||
├── LayoutVersionRepositoryInterface.php
|
||||
└── SystemConfigRepositoryInterface.php
|
||||
```
|
||||
|
||||
### 인터페이스 정의 패턴
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface UserRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 사용자 조회
|
||||
*
|
||||
* @param int $id
|
||||
* @return User|null
|
||||
*/
|
||||
public function findById(int $id): ?User;
|
||||
|
||||
/**
|
||||
* 사용자 목록 페이지네이션 조회
|
||||
*
|
||||
* @param array $filters 검색 조건
|
||||
* @return LengthAwarePaginator
|
||||
*/
|
||||
public function getPaginated(array $filters = []): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 사용자 생성
|
||||
*
|
||||
* @param array $data
|
||||
* @return User
|
||||
*/
|
||||
public function create(array $data): User;
|
||||
}
|
||||
```
|
||||
|
||||
### Repository 구현체 패턴
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Models\User;
|
||||
|
||||
class UserRepository implements UserRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 사용자 조회
|
||||
*/
|
||||
public function findById(int $id): ?User
|
||||
{
|
||||
return User::find($id);
|
||||
}
|
||||
|
||||
// ... 인터페이스 메서드 구현
|
||||
}
|
||||
```
|
||||
|
||||
### Service Provider 바인딩
|
||||
|
||||
`app/Providers/CoreServiceProvider.php`에서 인터페이스와 구현체를 바인딩합니다:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Repositories\UserRepository;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class CoreServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->registerRepositoryBindings();
|
||||
}
|
||||
|
||||
private function registerRepositoryBindings(): void
|
||||
{
|
||||
// bind() 사용 - Repository는 상태가 없으므로 매번 새 인스턴스
|
||||
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
|
||||
$this->app->bind(ModuleRepositoryInterface::class, ModuleRepository::class);
|
||||
// ... 나머지 Repository 바인딩
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 의존성 주입 패턴
|
||||
|
||||
#### Service에서 사용 (권장)
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
|
||||
class UserService
|
||||
{
|
||||
public function __construct(
|
||||
private UserRepositoryInterface $userRepository
|
||||
) {}
|
||||
|
||||
public function getUser(int $id): ?User
|
||||
{
|
||||
return $this->userRepository->findById($id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Controller에서 사용
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
|
||||
class UserController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserRepositoryInterface $userRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Console Command에서 사용
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ListModuleCommand extends Command
|
||||
{
|
||||
public function __construct(
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 인터페이스 장점
|
||||
|
||||
| 장점 | 설명 |
|
||||
|------|------|
|
||||
| **테스트 용이성** | Mock 객체로 쉽게 대체 가능 |
|
||||
| **유연한 구현체 교체** | 바인딩만 변경하면 다른 구현체 사용 가능 |
|
||||
| **명확한 계약** | 인터페이스가 Repository의 공개 API 명세 역할 |
|
||||
| **의존성 역전** | 고수준 모듈이 저수준 모듈에 의존하지 않음 |
|
||||
|
||||
---
|
||||
|
||||
## Service 클래스
|
||||
|
||||
### 역할
|
||||
|
||||
- 비즈니스 로직 구현
|
||||
- 훅 실행 (before/after)
|
||||
- 트랜잭션 관리
|
||||
- 여러 리포지토리 조율
|
||||
|
||||
### 패턴
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
|
||||
use App\Hooks\HookManager;
|
||||
use Modules\Sirsoft\Ecommerce\Contracts\Repositories\ProductRepositoryInterface;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(
|
||||
private ProductRepositoryInterface $productRepository
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 상품 생성
|
||||
*
|
||||
* @param array $data 상품 데이터
|
||||
* @return Product
|
||||
*/
|
||||
public function createProduct(array $data): Product
|
||||
{
|
||||
// Before 훅 - 데이터 검증, 전처리
|
||||
HookManager::doAction('sirsoft-ecommerce.product.before_create', $data);
|
||||
|
||||
// 필터 훅 - 데이터 변형
|
||||
$data = HookManager::applyFilters('sirsoft-ecommerce.product.filter_create_data', $data);
|
||||
|
||||
// 비즈니스 로직 실행
|
||||
$product = $this->productRepository->create($data);
|
||||
|
||||
// After 훅 - 후처리, 알림, 캐시 등
|
||||
HookManager::doAction('sirsoft-ecommerce.product.after_create', $product, $data);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 수정
|
||||
*
|
||||
* @param int $id 상품 ID
|
||||
* @param array $data 수정할 데이터
|
||||
* @return Product
|
||||
*/
|
||||
public function updateProduct(int $id, array $data): Product
|
||||
{
|
||||
HookManager::doAction('sirsoft-ecommerce.product.before_update', $id, $data);
|
||||
|
||||
$data = HookManager::applyFilters('sirsoft-ecommerce.product.filter_update_data', $data, $id);
|
||||
|
||||
$product = $this->productRepository->update($id, $data);
|
||||
|
||||
HookManager::doAction('sirsoft-ecommerce.product.after_update', $product, $data);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 목록 조회
|
||||
*
|
||||
* @param array $filters 검색 필터
|
||||
* @return Collection
|
||||
*/
|
||||
public function getProducts(array $filters = []): Collection
|
||||
{
|
||||
// Before 훅 - 검색 조건 전처리
|
||||
HookManager::doAction('sirsoft-ecommerce.product.before_list', $filters);
|
||||
|
||||
// 필터 훅 - 검색 조건 변형
|
||||
$filters = HookManager::applyFilters('sirsoft-ecommerce.product.filter_list_query', $filters);
|
||||
|
||||
$products = $this->productRepository->getAll($filters);
|
||||
|
||||
// 필터 훅 - 결과 데이터 변형
|
||||
$products = HookManager::applyFilters('sirsoft-ecommerce.product.filter_list_result', $products, $filters);
|
||||
|
||||
// After 훅 - 조회 후처리 (로깅, 캐싱 등)
|
||||
HookManager::doAction('sirsoft-ecommerce.product.after_list', $products, $filters);
|
||||
|
||||
return $products;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 상세 조회
|
||||
*
|
||||
* @param int $id 상품 ID
|
||||
* @return Product|null
|
||||
*/
|
||||
public function getProduct(int $id): ?Product
|
||||
{
|
||||
// Before 훅 - 조회 전처리
|
||||
HookManager::doAction('sirsoft-ecommerce.product.before_show', $id);
|
||||
|
||||
$product = $this->productRepository->findById($id);
|
||||
|
||||
if ($product) {
|
||||
// 필터 훅 - 조회 결과 변형 (조회수 증가, 관련 데이터 추가 등)
|
||||
$product = HookManager::applyFilters('sirsoft-ecommerce.product.filter_show_result', $product);
|
||||
|
||||
// After 훅 - 조회 후처리
|
||||
HookManager::doAction('sirsoft-ecommerce.product.after_show', $product);
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 훅 실행 순서
|
||||
|
||||
```
|
||||
1. Before Action Hook → 사전 처리, 검증
|
||||
2. Filter Hook → 데이터 변형
|
||||
3. Repository 호출 → 실제 데이터 작업
|
||||
4. After Action Hook → 후처리, 알림, 캐시
|
||||
```
|
||||
|
||||
### 훅 네이밍 규칙
|
||||
|
||||
```
|
||||
[vendor-module].[entity].[action]_[timing]
|
||||
|
||||
예시:
|
||||
sirsoft-ecommerce.product.before_create
|
||||
sirsoft-ecommerce.product.after_update
|
||||
sirsoft-ecommerce.product.filter_create_data
|
||||
```
|
||||
|
||||
### 서비스 내부 조건부 권한 체크
|
||||
|
||||
미들웨어가 아닌 **서비스 내부**에서 추가적인 권한 체크가 필요한 경우 `PermissionHelper`를 사용합니다.
|
||||
대표적인 예: 역할(role) 변경처럼 데이터의 일부 필드만 별도 권한이 필요한 경우.
|
||||
|
||||
```php
|
||||
use App\Helpers\PermissionHelper;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
public function updateUser(User $user, array $data): User
|
||||
{
|
||||
$roleIds = $data['role_ids'] ?? null;
|
||||
unset($data['role_ids'], $data['roles']);
|
||||
|
||||
// 훅 실행 (생략)...
|
||||
|
||||
$user = $this->userRepository->update($user->id, $data);
|
||||
|
||||
// 역할 변경은 별도 권한으로 보호
|
||||
if ($roleIds !== null) {
|
||||
$authUser = Auth::user();
|
||||
|
||||
// 자기 자신의 역할은 항상 변경 불가 (보안)
|
||||
if ($authUser && $authUser->id === $user->id) {
|
||||
$roleIds = null;
|
||||
}
|
||||
|
||||
// core.permissions.update 권한 없으면 역할 변경 무시
|
||||
if ($roleIds !== null && ! PermissionHelper::check('core.permissions.update', $authUser)) {
|
||||
$roleIds = null;
|
||||
}
|
||||
|
||||
if ($roleIds !== null) {
|
||||
$user->roles()->sync($roleIds);
|
||||
}
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
필수: 역할/권한 변경은 미들웨어 권한과 별개로 서비스에서 명시적 체크 필수
|
||||
필수: 자기 자신의 역할 변경은 항상 불가 (관리자 실수 방지)
|
||||
패턴: 민감 필드 분리 → 별도 권한 체크 → 권한 없으면 해당 필드 무시 (403이 아닌 무시)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 트랜잭션 및 관계 삭제 패턴
|
||||
|
||||
### CASCADE 방지 — 명시적 관계 삭제
|
||||
|
||||
```
|
||||
필수: Service에서 명시적 삭제 (DB CASCADE 의존 금지)
|
||||
필수: Service에서 모든 관계를 명시적으로 삭제 (훅/파일/로깅 보장)
|
||||
```
|
||||
|
||||
엔티티 삭제 시 관련된 모든 관계를 **Service에서 명시적으로** 제거합니다:
|
||||
|
||||
```php
|
||||
public function deleteUser(User $user): bool
|
||||
{
|
||||
// Before 훅
|
||||
HookManager::doAction('core.user.before_delete', $user);
|
||||
|
||||
// 원본 데이터 보관 (after 훅에서 사용)
|
||||
$userData = $user->toArray();
|
||||
|
||||
// 관계 명시적 해제 (CASCADE 의존 금지)
|
||||
$user->roles()->detach(); // 다대다 관계 해제
|
||||
$user->consents()->delete(); // 일대다 관계 삭제
|
||||
$user->tokens()->delete(); // 인증 토큰 삭제
|
||||
|
||||
// Attachment 삭제 (비즈니스 로직 통한 삭제)
|
||||
if ($user->avatarAttachment) {
|
||||
$this->attachmentService->delete($user->avatarAttachment->id);
|
||||
}
|
||||
|
||||
$result = $this->userRepository->delete($user);
|
||||
|
||||
// After 훅 (원본 데이터 전달)
|
||||
HookManager::doAction('core.user.after_delete', $userData);
|
||||
|
||||
return $result;
|
||||
}
|
||||
```
|
||||
|
||||
### 일괄 업데이트 트랜잭션 패턴
|
||||
|
||||
```php
|
||||
public function bulkUpdateStatus(array $ids, string $status): int
|
||||
{
|
||||
$statusEnum = UserStatus::from($status);
|
||||
|
||||
$updatedCount = DB::transaction(function () use ($ids, $statusEnum) {
|
||||
$count = User::whereIn('id', $ids)->update([
|
||||
'status' => $statusEnum->value,
|
||||
]);
|
||||
|
||||
// 트랜잭션 내에서 관계형 데이터 명시적 삭제
|
||||
if ($statusEnum !== UserStatus::Active) {
|
||||
PersonalAccessToken::where('tokenable_type', User::class)
|
||||
->whereIn('tokenable_id', $ids)
|
||||
->delete();
|
||||
}
|
||||
|
||||
return $count;
|
||||
});
|
||||
|
||||
// 트랜잭션 외부에서 훅 실행 (실패 시 롤백 방지)
|
||||
HookManager::doAction('core.user.after_bulk_update', $ids, $status, $updatedCount);
|
||||
|
||||
return $updatedCount;
|
||||
}
|
||||
```
|
||||
|
||||
### 핵심 규칙
|
||||
|
||||
| 원칙 | 설명 |
|
||||
| ------ | ------ |
|
||||
| **CASCADE 금지** | DB 외래키 CASCADE 대신 Service에서 명시적 삭제 |
|
||||
| **원본 데이터 보관** | 삭제 전 `toArray()`로 캡처 → after 훅에서 사용 |
|
||||
| **관계 유형별 처리** | `detach()` (다대다), `delete()` (일대다), Service 호출 (복합) |
|
||||
| **트랜잭션 내 훅 금지** | 훅은 트랜잭션 **외부**에서 실행 (롤백 시 훅 부작용 방지) |
|
||||
| **AttachmentService 사용** | 파일 삭제는 직접 DB 삭제 대신 AttachmentService 통해 처리 |
|
||||
|
||||
---
|
||||
|
||||
## 상태 변경 자동 처리
|
||||
|
||||
상태(status) 변경 시 관련 타임스탬프와 토큰을 자동으로 처리하는 패턴입니다.
|
||||
|
||||
### 상태 변경 타임스탬프 자동 설정
|
||||
|
||||
상태 변경 시 관련 타임스탬프를 `match` 표현식으로 자동 설정합니다:
|
||||
|
||||
```php
|
||||
// 상태 변경 감지 및 타임스탬프 자동 설정
|
||||
$oldStatus = $user->status;
|
||||
$newStatus = $data['status'] ?? null;
|
||||
|
||||
if ($newStatus && $newStatus !== $oldStatus) {
|
||||
$newStatusEnum = UserStatus::from($newStatus);
|
||||
$data = match ($newStatusEnum) {
|
||||
UserStatus::Blocked => array_merge($data, ['blocked_at' => now()]),
|
||||
UserStatus::Withdrawn => array_merge($data, ['withdrawn_at' => now()]),
|
||||
UserStatus::Active => array_merge($data, ['blocked_at' => null, 'withdrawn_at' => null]),
|
||||
UserStatus::Inactive => $data, // 타임스탬프 변경 없음
|
||||
};
|
||||
}
|
||||
|
||||
$this->userRepository->update($user, $data);
|
||||
```
|
||||
|
||||
### 상태 변경 시 토큰 자동 삭제
|
||||
|
||||
Active 외 상태로 변경 시 해당 사용자의 토큰을 삭제하여 즉시 로그아웃시킵니다:
|
||||
|
||||
```php
|
||||
// 단일 사용자: 상태가 Active 외로 변경되었으면 토큰 삭제
|
||||
if ($newStatus && $newStatus !== $oldStatus && $newStatus !== UserStatus::Active->value) {
|
||||
$user->tokens()->delete();
|
||||
}
|
||||
|
||||
// 일괄 업데이트: PersonalAccessToken 직접 삭제
|
||||
if ($statusEnum !== UserStatus::Active) {
|
||||
PersonalAccessToken::where('tokenable_type', User::class)
|
||||
->whereIn('tokenable_id', $ids)
|
||||
->delete();
|
||||
}
|
||||
```
|
||||
|
||||
### 패턴 요약
|
||||
|
||||
| 원칙 | 설명 |
|
||||
| ---------- | ---------- |
|
||||
| **변경 감지** | `$oldStatus !== $newStatus` 비교 후 처리 (불필요한 업데이트 방지) |
|
||||
| **match 표현식** | Enum case별 타임스탬프 자동 매핑 (`array_merge`로 기존 데이터 보존) |
|
||||
| **Active 복귀 시 초기화** | `blocked_at`, `withdrawn_at` 등 관련 타임스탬프를 `null`로 리셋 |
|
||||
| **토큰 자동 삭제** | 비활성 상태 전환 시 즉시 로그아웃 (단일: `tokens()->delete()`, 일괄: `PersonalAccessToken` 직접 삭제) |
|
||||
|
||||
---
|
||||
|
||||
## Repository 클래스
|
||||
|
||||
### 역할
|
||||
|
||||
- 데이터 액세스 추상화
|
||||
- 쿼리 로직 캡슐화
|
||||
- N+1 문제 방지 (Eager Loading)
|
||||
|
||||
### 데이터베이스 독립성 원칙
|
||||
|
||||
```
|
||||
필수: 표준 SQL만 사용 (MySQL 전용 함수 금지)
|
||||
필수: Laravel 쿼리빌더 또는 Eloquent 문법 사용
|
||||
✅ 필수: 데이터베이스 추상화 계층을 통한 쿼리 작성
|
||||
```
|
||||
|
||||
특정 데이터베이스에 의존하는 Raw 쿼리를 사용하면 다른 데이터베이스로 마이그레이션이 어려워집니다.
|
||||
|
||||
#### JSON 컬럼 처리
|
||||
|
||||
```php
|
||||
// ❌ DON'T: MySQL 전용 함수 사용
|
||||
$query->whereRaw("JSON_SEARCH(name, 'one', ?) IS NOT NULL", ["%{$keyword}%"]);
|
||||
$query->orderByRaw("JSON_EXTRACT(name, '$.\"$locale\"') $sortOrder");
|
||||
|
||||
// ✅ DO: Laravel JSON 문법 사용
|
||||
$locales = config('app.translatable_locales', ['ko', 'en']);
|
||||
foreach ($locales as $locale) {
|
||||
$query->orWhere("name->{$locale}", 'like', "%{$keyword}%");
|
||||
}
|
||||
$query->orderBy("name->{$locale}", $sortOrder);
|
||||
```
|
||||
|
||||
#### 허용되는 Raw 쿼리
|
||||
|
||||
복잡한 집계나 Laravel이 지원하지 않는 기능에 한해 Raw 쿼리를 허용하되, 가능한 표준 SQL을 사용합니다:
|
||||
|
||||
```php
|
||||
// ✅ 표준 SQL 집계 (대부분의 DB에서 호환)
|
||||
$query->selectRaw('sales_status, COUNT(*) as count');
|
||||
$query->whereColumn('stock_quantity', '<=', 'safe_stock_quantity');
|
||||
```
|
||||
|
||||
### 패턴
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class ProductRepository
|
||||
{
|
||||
/**
|
||||
* 모든 상품 조회
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
public function getAll(): Collection
|
||||
{
|
||||
return Product::with(['category', 'images'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 상품 조회
|
||||
*
|
||||
* @param int $id
|
||||
* @return Product|null
|
||||
*/
|
||||
public function findById(int $id): ?Product
|
||||
{
|
||||
return Product::with(['category', 'images'])->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 생성
|
||||
*
|
||||
* @param array $data
|
||||
* @return Product
|
||||
*/
|
||||
public function create(array $data): Product
|
||||
{
|
||||
return Product::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 수정
|
||||
*
|
||||
* @param int $id
|
||||
* @param array $data
|
||||
* @return Product
|
||||
*/
|
||||
public function update(int $id, array $data): Product
|
||||
{
|
||||
$product = $this->findById($id);
|
||||
$product->update($data);
|
||||
return $product->fresh();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Eager Loading으로 N+1 방지
|
||||
|
||||
```php
|
||||
// ❌ DON'T: N+1 문제 발생
|
||||
public function getAll(): Collection
|
||||
{
|
||||
return Product::all(); // 관계 로딩 없음
|
||||
}
|
||||
|
||||
// ✅ DO: Eager Loading 사용
|
||||
public function getAll(): Collection
|
||||
{
|
||||
return Product::with(['category', 'images'])->get();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 다중 검색 필터 Trait (HasMultipleSearchFilters)
|
||||
|
||||
목록 API에서 다중 검색 조건을 지원해야 할 때 `HasMultipleSearchFilters` Trait을 사용합니다.
|
||||
|
||||
### 파일 위치
|
||||
|
||||
`app/Repositories/Concerns/HasMultipleSearchFilters.php`
|
||||
|
||||
### 지원 연산자
|
||||
|
||||
| 연산자 | 설명 | SQL 변환 |
|
||||
|--------|------|----------|
|
||||
| `like` (기본) | 부분 일치 | `LIKE %value%` |
|
||||
| `eq` | 정확히 일치 | `= value` |
|
||||
| `starts_with` | 시작 일치 | `LIKE value%` |
|
||||
| `ends_with` | 끝 일치 | `LIKE %value` |
|
||||
|
||||
### Trait 제공 메서드
|
||||
|
||||
| 메서드 | 설명 |
|
||||
|--------|------|
|
||||
| `applyMultipleSearchFilters()` | 다중 검색 조건을 AND로 적용 |
|
||||
| `applySearchFilter()` | 개별 검색 필터 적용 (연산자 처리) |
|
||||
| `applyOrSearchAcrossFields()` | 단일 검색어로 여러 필드 OR 검색 |
|
||||
|
||||
### Repository에서 사용
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Repositories\Concerns\HasMultipleSearchFilters;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class UserRepository
|
||||
{
|
||||
use HasMultipleSearchFilters;
|
||||
|
||||
/**
|
||||
* 검색 가능한 필드 목록 (보안을 위해 허용 필드 명시)
|
||||
*/
|
||||
private const SEARCHABLE_FIELDS = ['name', 'email', 'username'];
|
||||
|
||||
/**
|
||||
* 필터링 및 페이지네이션 적용
|
||||
*/
|
||||
public function getPaginatedUsers(array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
$query = User::query();
|
||||
$this->applyFilters($query, $filters);
|
||||
return $query->paginate($filters['per_page'] ?? 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리에 필터 조건 적용
|
||||
*/
|
||||
private function applyFilters(Builder $query, array $filters): void
|
||||
{
|
||||
// 다중 검색 조건 적용
|
||||
if (! empty($filters['filters']) && is_array($filters['filters'])) {
|
||||
$this->applyMultipleSearchFilters($query, $filters['filters'], self::SEARCHABLE_FIELDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### FormRequest 검증 규칙
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UserListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 검색 가능한 필드 목록 (보안을 위해 허용 필드 명시)
|
||||
*/
|
||||
public const SEARCHABLE_FIELDS = ['name', 'email', 'username'];
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
// 'all'은 전체 필드 검색을 의미하는 특수 값
|
||||
$searchableFields = implode(',', array_merge(['all'], self::SEARCHABLE_FIELDS));
|
||||
|
||||
return [
|
||||
// 다중 검색 조건
|
||||
'filters' => 'nullable|array|max:10',
|
||||
'filters.*.field' => "required_with:filters|string|in:{$searchableFields}",
|
||||
'filters.*.value' => 'required_with:filters|string|max:255',
|
||||
'filters.*.operator' => 'nullable|string|in:like,eq,starts_with,ends_with',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 데이터 전처리
|
||||
*
|
||||
* 프론트엔드에서 빈 필터가 전송되는 경우를 처리합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
// value가 비어있는 filters 자동 제거
|
||||
$filters = $this->filters;
|
||||
if (is_array($filters)) {
|
||||
$filters = array_filter($filters, function ($filter) {
|
||||
return ! empty($filter['value']);
|
||||
});
|
||||
// 인덱스 재정렬
|
||||
$filters = array_values($filters);
|
||||
$this->merge(['filters' => $filters ?: null]);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 빈 필터 자동 제거 패턴
|
||||
|
||||
프론트엔드(DataSourceManager)에서 파라미터 치환 시 빈 값이 전송될 수 있습니다. 이를 처리하기 위해 `prepareForValidation()`에서 빈 필터를 자동 제거합니다:
|
||||
|
||||
| 상황 | 처리 방식 |
|
||||
|------|----------|
|
||||
| `filters[0][value]`가 빈 문자열 | 해당 filter 항목 제거 |
|
||||
| 모든 filters가 제거됨 | `filters`를 `null`로 설정 |
|
||||
| 유효한 필터만 존재 | 인덱스 재정렬 후 검증 진행 |
|
||||
|
||||
### 'all' 필드 검색
|
||||
|
||||
`field`가 `'all'`인 경우 모든 SEARCHABLE_FIELDS를 OR 조건으로 검색합니다. HasMultipleSearchFilters Trait에서 이를 처리합니다.
|
||||
|
||||
### API 사용 예시
|
||||
|
||||
```bash
|
||||
# 단일 필터
|
||||
GET /api/admin/users?filters[0][field]=name&filters[0][value]=홍
|
||||
|
||||
# 다중 필터 (AND 조건)
|
||||
GET /api/admin/users?filters[0][field]=name&filters[0][value]=홍&filters[1][field]=email&filters[1][value]=example
|
||||
|
||||
# 연산자 지정
|
||||
GET /api/admin/users?filters[0][field]=name&filters[0][value]=홍길동&filters[0][operator]=eq
|
||||
```
|
||||
|
||||
### 다른 Repository에서 재사용
|
||||
|
||||
```php
|
||||
class ProductRepository
|
||||
{
|
||||
use HasMultipleSearchFilters;
|
||||
|
||||
private const SEARCHABLE_FIELDS = ['name', 'sku', 'description'];
|
||||
|
||||
// 동일한 패턴으로 검색 구현
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 모듈에서 Repository 인터페이스 바인딩
|
||||
|
||||
모듈 내에서 Repository를 사용할 때도 반드시 인터페이스를 통해 DI해야 합니다.
|
||||
|
||||
### 모듈 Repository 구조
|
||||
|
||||
```text
|
||||
modules/sirsoft-ecommerce/src/
|
||||
├── Contracts/
|
||||
│ └── Repositories/
|
||||
│ └── ProductRepositoryInterface.php
|
||||
├── Repositories/
|
||||
│ └── ProductRepository.php
|
||||
├── Services/
|
||||
│ └── ProductService.php
|
||||
└── Providers/
|
||||
└── EcommerceServiceProvider.php
|
||||
```
|
||||
|
||||
### 모듈 인터페이스 정의
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Contracts\Repositories;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
interface ProductRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?Product;
|
||||
public function getPaginated(array $filters = []): LengthAwarePaginator;
|
||||
public function create(array $data): Product;
|
||||
public function update(int $id, array $data): Product;
|
||||
public function delete(int $id): bool;
|
||||
}
|
||||
```
|
||||
|
||||
### 모듈 ServiceProvider에서 바인딩
|
||||
|
||||
모듈의 ServiceProvider에서 인터페이스와 구현체를 바인딩합니다:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Modules\Sirsoft\Ecommerce\Contracts\Repositories\ProductRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\ProductRepository;
|
||||
|
||||
class EcommerceServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->registerRepositoryBindings();
|
||||
}
|
||||
|
||||
private function registerRepositoryBindings(): void
|
||||
{
|
||||
$this->app->bind(ProductRepositoryInterface::class, ProductRepository::class);
|
||||
// 추가 Repository 바인딩...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 모듈 Service에서 인터페이스 사용
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Contracts\Repositories\ProductRepositoryInterface;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(
|
||||
private ProductRepositoryInterface $productRepository // ✅ 인터페이스 타입힌트
|
||||
) {}
|
||||
}
|
||||
```
|
||||
|
||||
### 올바른 사용 vs 잘못된 사용
|
||||
|
||||
```php
|
||||
// ❌ DON'T: 구체 클래스 직접 타입힌트
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\ProductRepository;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(
|
||||
private ProductRepository $productRepository // 구체 클래스 직접 의존
|
||||
) {}
|
||||
}
|
||||
|
||||
// ✅ DO: 인터페이스 타입힌트
|
||||
use Modules\Sirsoft\Ecommerce\Contracts\Repositories\ProductRepositoryInterface;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(
|
||||
private ProductRepositoryInterface $productRepository // 인터페이스에 의존
|
||||
) {}
|
||||
}
|
||||
```
|
||||
|
||||
### 핵심 원칙 요약
|
||||
|
||||
| 원칙 | 설명 |
|
||||
|------|------|
|
||||
| **인터페이스 의존** | Service/Controller는 Repository 인터페이스에 의존 |
|
||||
| **ServiceProvider 바인딩** | 인터페이스-구현체 매핑은 ServiceProvider에서 수행 |
|
||||
| **테스트 용이성** | Mock 객체로 쉽게 대체 가능 |
|
||||
| **유연한 교체** | 바인딩만 변경하면 다른 구현체 사용 가능 |
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [컨트롤러 계층 구조](controllers.md) - Controller에서 Service 사용
|
||||
- [검증 로직 구현](validation.md) - FormRequest 검증 규칙
|
||||
- [index.md](index.md) - 백엔드 가이드 전체 목차
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user