v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
# 그누보드7 확장 시스템 개발 가이드
> 이 문서는 그누보드7의 확장 시스템 전체 개요와 각 상세 문서에 대한 링크를 제공합니다.
---
## 핵심 원칙
```text
필수: /modules, /plugins 디렉토리 스캔으로 자동 발견 (composer.json 하드코딩 금지)
필수: 모든 확장 작업은 Artisan 커맨드로 수행
✅ 필수: 훅 시스템을 통한 코어 수정 최소화
```
---
## 확장 시스템 개요
G7은 **동적 로딩** 기반의 확장 시스템을 제공합니다:
- **모듈**: 독립적인 비즈니스 기능 단위 (예: 이커머스, 블로그)
- **플러그인**: 특정 기능 확장 (예: 결제, 배송)
- **템플릿**: UI 렌더링 및 레이아웃 정의 (Admin, User)
- **훅 시스템**: 코어 수정 없이 로직 확장
---
## 문서 구조
### 훅 시스템
| 문서 | 설명 |
|------|------|
| [hooks.md](hooks.md) | Action/Filter Hook, 리스너 구현, 우선순위 |
### 모듈 개발
| 문서 | 설명 |
|------|------|
| [module-basics.md](module-basics.md) | AbstractModule, 디렉토리 구조, 네이밍 규칙 |
| [module-routing.md](module-routing.md) | API/Web 라우트, 자동 Prefix, routes.json |
| [module-layouts.md](module-layouts.md) | 레이아웃 등록, 오버라이드, 상속 |
| [module-commands.md](module-commands.md) | Artisan 커맨드 (install, activate, uninstall) |
| [module-i18n.md](module-i18n.md) | 백엔드/프론트엔드 다국어 분리 |
### 레이아웃 확장
| 문서 | 설명 |
|------|------|
| [layout-extensions.md](layout-extensions.md) | 동적 UI 주입 (Overlay, Extension Point), 템플릿 오버라이드 |
### 플러그인 개발
| 문서 | 설명 |
|------|------|
| [plugin-development.md](plugin-development.md) | PluginInterface, 격리성, 의존성 원칙 |
### 확장 관리자
| 문서 | 설명 |
|------|------|
| [extension-manager.md](extension-manager.md) | Composer 오토로드, 서비스 등록 |
### 템플릿 시스템
| 문서 | 설명 |
|------|------|
| [template-basics.md](template-basics.md) | Admin/User 템플릿, 메타데이터, 버전 히스토리 |
| [template-routing.md](template-routing.md) | 라우트 정의, 언어 파일 경로 규칙 |
| [template-security.md](template-security.md) | API 서빙, 파일 확장자 화이트리스트 |
| [template-caching.md](template-caching.md) | 캐시 계층, 무효화 전략 |
| [template-commands.md](template-commands.md) | Artisan 커맨드 (install, activate) |
### 권한 및 메뉴 시스템
| 문서 | 설명 |
|------|------|
| [permissions.md](permissions.md) | Role, Permission, 자동 관리 |
| [menus.md](menus.md) | 메뉴 권한, 시더 |
---
## 확장 타입별 네이밍 규칙
| 타입 | 디렉토리명 | 네임스페이스 | Composer 경로 |
|------|-----------|-------------|---------------|
| 모듈 | `vendor-module` | `Modules\Vendor\Module\` | `modules/vendor-module` |
| 플러그인 | `vendor-plugin` | `Plugins\Vendor\Plugin\` | `plugins/vendor-plugin` |
| 템플릿 | `vendor-template` | - | `templates/vendor-template` |
**예시**:
- 모듈: `sirsoft-ecommerce` → `Modules\Sirsoft\Ecommerce\`
- 플러그인: `sirsoft-payment` → `Plugins\Sirsoft\Payment\`
- 템플릿: `sirsoft-admin_basic`
---
## 훅 네이밍 규칙
```
[vendor-module].[entity].[action]_[timing]
```
**타이밍 접미사**:
- `before_*`: 작업 실행 전
- `after_*`: 작업 실행 후
- `on_*`: 특정 이벤트 발생 시
- `filter_*`: 데이터 필터링
**예시**:
```
sirsoft-ecommerce.product.before_create
sirsoft-ecommerce.product.after_update
sirsoft-ecommerce.product.filter_create_data
sirsoft-ecommerce.order.on_payment_success
```
---
## 주요 Artisan 커맨드
### 모듈 관련
```bash
php artisan module:list # 모듈 목록 조회
php artisan module:install [identifier] # 모듈 설치
php artisan module:activate [identifier] # 모듈 활성화
php artisan module:deactivate [identifier] # 모듈 비활성화
php artisan module:uninstall [identifier] # 모듈 제거
php artisan module:cache-clear # 모듈 캐시 정리
```
### 템플릿 관련
```bash
php artisan template:list # 템플릿 목록 조회
php artisan template:install [identifier] # 템플릿 설치
php artisan template:activate [identifier] # 템플릿 활성화
php artisan template:deactivate [identifier] # 템플릿 비활성화
php artisan template:uninstall [identifier] # 템플릿 제거
php artisan template:cache-clear # 템플릿 캐시 정리
```
### 확장 관리자
```bash
php artisan extension:update-autoload # Composer 오토로드 업데이트
```
---
## 빠른 시작 가이드
### 새 모듈 개발 시
1. [module-basics.md](module-basics.md) - 기본 구조 이해
2. [module-routing.md](module-routing.md) - 라우트 설정
3. [module-i18n.md](module-i18n.md) - 다국어 지원
4. [module-layouts.md](module-layouts.md) - 레이아웃 등록 (필요시)
5. [hooks.md](hooks.md) - 훅 리스너 구현 (필요시)
### 새 플러그인 개발 시
1. [plugin-development.md](plugin-development.md) - 플러그인 구조 이해
2. [hooks.md](hooks.md) - 훅 리스너 구현
### 템플릿 커스터마이징 시
1. [template-basics.md](template-basics.md) - 템플릿 타입 이해
2. [template-routing.md](template-routing.md) - 라우트/언어 파일
3. [template-security.md](template-security.md) - 보안 규칙
---
## 관련 문서
- [AGENTS.md](../../../AGENTS.md) - 프로젝트 개발 가이드
- [backend/](../backend/) - 백엔드 개발 가이드
- [frontend/](../frontend/) - 프론트엔드 개발 가이드
- [database-guide.md](../database-guide.md) - 데이터베이스 가이드
+213
View File
@@ -0,0 +1,213 @@
# Changelog 규칙 (Changelog Rules)
> 코어 및 확장(모듈, 플러그인, 템플릿)의 변경사항을 CHANGELOG.md에 기록하는 규정
## TL;DR (5초 요약)
```text
1. 확장/코어 버전 업 시 CHANGELOG.md에 변경사항 기록 필수 (미기록 시 버전 업 불가)
2. 형식: Keep a Changelog 표준 (## [버전] - 날짜 / ### 카테고리 / - 항목)
3. 허용 카테고리: Added, Changed, Deprecated, Removed, Fixed, Security
4. 확장 위치: 각 확장의 루트 디렉토리 (modules/_bundled/vendor-module/CHANGELOG.md)
5. 코어 위치: 프로젝트 루트 /CHANGELOG.md (코어 버전 변경 시 필수)
```
---
## 목차
1. [CHANGELOG.md 작성 규칙](#1-changelogmd-작성-규칙)
2. [카테고리 정의](#2-카테고리-정의)
3. [파일 위치](#3-파일-위치)
4. [ChangelogParser 헬퍼](#4-changelogparser-헬퍼)
5. [API 엔드포인트](#5-api-엔드포인트)
6. [관리 화면 표시](#6-관리-화면-표시)
7. [템플릿 예시](#7-템플릿-예시)
---
## 1. CHANGELOG.md 작성 규칙
### 필수 사항
```text
확장 버전 업 시 CHANGELOG.md에 변경사항 기록 필수
미기록 시 버전 업 작업 불완전으로 간주
```
- **형식**: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) 표준 준수
- **버전 관리**: [Semantic Versioning](https://semver.org/lang/ko/) 준수
- **작성 언어**: 한국어 (확장 대상이 한국어 사용자)
- **날짜 형식**: YYYY-MM-DD (ISO 8601)
- **최신 버전**: 파일 상단에 위치 (역순)
### 버전 섹션 형식
```markdown
## [버전] - YYYY-MM-DD
```
예: `## [0.1.2] - 2026-02-25`
### 항목 형식
```markdown
### 카테고리
- 변경사항 설명
```
---
## 2. 카테고리 정의
| 카테고리 | 설명 | 사용 시점 |
|----------|------|----------|
| `Added` | 새 기능 추가 | 새로운 기능, 화면, API 엔드포인트 추가 |
| `Changed` | 기존 기능 변경 | 기존 동작 수정, 성능 개선, UI 변경 |
| `Deprecated` | 향후 제거 예정 | 향후 삭제될 기능 경고 |
| `Removed` | 기능 제거 | 기존 기능/API 삭제 |
| `Fixed` | 버그 수정 | 기존 버그, 오류 수정 |
| `Security` | 보안 취약점 수정 | 보안 관련 수정 |
---
## 3. 파일 위치
### 확장 (모듈/플러그인/템플릿)
```text
modules/_bundled/vendor-module/CHANGELOG.md # 모듈 (예: sirsoft-board)
plugins/_bundled/vendor-plugin/CHANGELOG.md # 플러그인 (예: sirsoft-tosspayments)
templates/_bundled/vendor-template/CHANGELOG.md # 템플릿 (예: sirsoft-admin_basic)
```
- _bundled 디렉토리에서 작업 (활성 디렉토리 직접 수정 금지)
- 업데이트 프로세스를 통해 활성 디렉토리로 복사
### 코어
```text
/CHANGELOG.md # 프로젝트 루트
```
- **코어 버전 변경 시 CHANGELOG.md에 변경사항 기록 필수** (미기록 시 버전 업 불가)
- 확장과 동일한 Keep a Changelog 형식 사용
- 코어 버전 변경 대상 파일: `config/app.php`, `.env.example`, `.env.testing`
- 버전 변경 시 반드시 CHANGELOG.md에 해당 버전 섹션 추가 후 버전 파일 수정
---
## 4. ChangelogParser 헬퍼
**파일**: `app/Extension/Helpers/ChangelogParser.php`
### 주요 메서드
| 메서드 | 설명 | 반환 |
|--------|------|------|
| `parse(string $filePath)` | CHANGELOG.md 전체 파싱 | `array` (버전별 구조화 배열) |
| `getVersionRange(string $filePath, string $from, string $to)` | 특정 범위 엔트리 추출 | `array` (from 초과 ~ to 이하) |
| `resolveChangelogPath(string $basePath, string $identifier, ?string $source)` | 소스별 경로 결정 | `?string` |
### 반환 형식
```php
[
[
'version' => '0.1.2',
'date' => '2026-02-25',
'categories' => [
['name' => 'Added', 'items' => ['새 기능 A']],
['name' => 'Fixed', 'items' => ['버그 B 수정']],
],
],
]
```
---
## 5. API 엔드포인트
```text
GET /api/admin/modules/{identifier}/changelog
GET /api/admin/plugins/{identifier}/changelog
GET /api/admin/templates/{identifier}/changelog
```
### 쿼리 파라미터
| 파라미터 | 설명 | 기본값 |
|----------|------|--------|
| `source` | CHANGELOG.md 읽을 위치 | `active` |
| `from_version` | 이 버전 초과 항목만 반환 | - |
| `to_version` | 이 버전 이하만 반환 | - |
### 사용 시나리오
- **상세 모달**: `GET .../changelog` (전체 조회)
- **업데이트 모달**: `GET .../changelog?source=bundled&from_version=0.1.1&to_version=0.1.2` (변경분)
---
## 6. 관리 화면 표시
### 업데이트 모달
- **전역 상태**: `_global.updateChangelog` (3개 확장 타입 공통)
- **표시 조건**: `updateChangelog && updateChangelog.length > 0`
- **표시 위치**: 버전 정보 아래, 외부 링크(github_changelog_url) 위
- **스타일**: blue 배경 (`bg-blue-50 dark:bg-blue-900/20`)
- **우선순위**: 인라인 changelog > 외부 링크 (둘 다 있으면 둘 다 표시)
### 상세 모달
- **전역 상태**: `_global.moduleChangelog`, `_global.pluginChangelog`, `_global.templateChangelog` (타입별)
- **섹션 ID**: `changelog_section`
- **아이콘**: `clock-rotate-left`
- **empty state**: `_global.xxxChangelog`가 비어있으면 "변경 내역 정보가 없습니다." 표시
### 메인 리스트 액션 흐름
```text
# 업데이트 버튼 클릭 시:
setState(selectedX) → apiCall(changelog?source=bundled&from_version=...&to_version=...)
→ onSuccess: setState(updateChangelog) + openModal(update_modal)
→ onError: setState(updateChangelog=[]) + openModal(update_modal)
# 상세 보기 버튼 클릭 시:
setState(selectedX) → apiCall(changelog)
→ onSuccess: setState(xChangelog) + openModal(detail_modal)
→ onError: setState(xChangelog=[]) + openModal(detail_modal)
```
---
## 7. 템플릿 예시
새 확장을 만들 때 아래 템플릿을 사용합니다:
```markdown
# Changelog
이 프로젝트의 모든 주요 변경사항을 기록합니다.
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [0.1.0] - YYYY-MM-DD
### Added
- 초기 기능 구현
```
---
## 관련 파일
- `app/Extension/Helpers/ChangelogParser.php` — Changelog 파서
- `app/Http/Requests/Extension/ChangelogRequest.php` — FormRequest 검증
- `app/Http/Controllers/Api/Admin/ModuleController.php` — `changelog()` 메서드
- `app/Http/Controllers/Api/Admin/PluginController.php` — `changelog()` 메서드
- `app/Http/Controllers/Api/Admin/TemplateController.php` — `changelog()` 메서드
- `app/Services/ModuleService.php` — `getModuleChangelog()` 메서드
- `app/Services/PluginService.php` — `getPluginChangelog()` 메서드
- `app/Services/TemplateService.php` — `getTemplateChangelog()` 메서드
+349
View File
@@ -0,0 +1,349 @@
# ExtensionManager (확장 관리자)
> **소스**: extension-guide.md에서 분리
> **관련 문서**: [module-basics.md](module-basics.md), [plugin-development.md](plugin-development.md)
---
## TL;DR (5초 요약)
```text
1. composer.json 수정 없음 - 런타임 오토로드 방식 사용
2. 캐시 파일: bootstrap/cache/autoload-extensions.php (gitignore 대상)
3. 설치/삭제 시 자동 갱신: updateComposerAutoload() → generateAutoloadFile()
4. 수동 갱신: php artisan extension:update-autoload
5. _bundled/_pending 디렉토리 자동 제외 (str_starts_with($name, '_') → skip)
```
---
## 목차
1. [개요](#개요)
2. [런타임 오토로드 방식](#런타임-오토로드-방식)
3. [Composer 의존성 관리](#composer-의존성-관리)
4. [식별자 검증 규칙](#식별자-검증-규칙-validextensionidentifier)
5. [Artisan 커맨드](#artisan-커맨드)
6. [서비스 등록](#서비스-등록)
---
## 개요
모듈과 플러그인에서 공통으로 사용되는 기능을 담당하는 관리자 클래스입니다. 주로 오토로드 설정 관리를 담당합니다.
**주요 역할**:
- 런타임 오토로드 캐시 파일 생성
- 모듈/플러그인 설치 시 PSR-4 네임스페이스 등록
- Composer ClassLoader에 동적 등록
---
## 런타임 오토로드 방식
### 핵심 원칙
```
중요: composer.json을 수정하지 않음
✅ 결정: 런타임 오토로드 방식 사용 (캐시 파일 기반)
✅ 장점: 버전 관리 충돌 없음, composer dump-autoload 불필요
```
### 동작 방식
```
모듈/플러그인 설치/삭제 시
↓
ExtensionManager::updateComposerAutoload() 호출
↓
bootstrap/cache/autoload-extensions.php 파일 생성 (gitignore 대상)
↓
public/index.php 또는 artisan 실행 시
↓
$loader->addPsr4()로 런타임에 네임스페이스 등록
```
### 캐시 파일 구조
```php
// bootstrap/cache/autoload-extensions.php
return [
'psr4' => [
"Modules\\Sirsoft\\Ecommerce\\" => "modules/sirsoft-ecommerce/src/",
"Plugins\\Sirsoft\\Payment\\" => "plugins/sirsoft-payment/src/",
],
'classmap' => [
"modules/sirsoft-ecommerce/module.php",
"plugins/sirsoft-payment/plugin.php",
],
'files' => [],
'vendor_autoloads' => [
"modules/sirsoft-ecommerce/vendor/autoload.php",
],
];
```
- `vendor_autoloads`: 모듈/플러그인의 `vendor/autoload.php` 경로 목록 (Composer 의존성이 설치된 경우만 포함)
### 중요 규칙
```
설치된 모듈/플러그인만 캐시 파일에 반영됩니다
_bundled/_pending 디렉토리는 활성 확장으로 인식하지 않습니다
```
- 디렉토리에 파일이 있어도 **DB에 설치 기록이 없으면 반영되지 않음**
- identifier는 디렉토리명과 동일 (예: `sirsoft-sample`, `sirsoft-payment`)
- `_`로 시작하는 디렉토리(`_bundled`, `_pending`)는 디렉토리 스캔 시 자동 제외됨
- 캐시 파일에는 활성 디렉토리 경로만 포함 (`_bundled/` 경로 미포함)
### 수행 작업
1. `ModuleRepository`와 `PluginRepository`를 통해 설치된 확장 목록 조회
2. 각 모듈/플러그인의 `composer.json`에서 PSR-4 오토로드 정보 수집
3. `bootstrap/cache/autoload-extensions.php` 파일 생성
4. `module.php`, `plugin.php` 파일을 `classmap`에 추가
### 로딩 진입점
**public/index.php** 및 **artisan**에서 `ExtensionManager::registerExtensionAutoload($loader)` 호출:
```text
registerExtensionAutoload($loader)
↓ 1. PSR-4 네임스페이스 등록 ($loader->addPsr4())
↓ 2. Classmap 파일 로드 (module.php, plugin.php → require_once)
↓ 3. Files 로드 (헬퍼 함수 등 → require_once)
↓ 4. Vendor autoloads 로드 (모듈/플러그인의 vendor/autoload.php → require_once)
```
**로딩 순서가 중요합니다**:
| 순서 | 유형 | 설명 |
| ---------- | ---------- | ---------- |
| 1 | PSR-4 | 확장의 `src/` 디렉토리 네임스페이스를 Composer ClassLoader에 등록 |
| 2 | Classmap | `module.php`, `plugin.php` 엔트리 파일을 즉시 로드 |
| 3 | Files | 헬퍼 함수 등 자동 로드 파일 |
| 4 | Vendor autoloads | 각 확장의 `vendor/autoload.php`를 `require_once`하여 외부 패키지 로드 |
- 캐시 파일 미존재 시 아무 작업도 하지 않고 return (설치 전 상태)
- 경로가 존재하지 않는 항목은 자동 스킵 (`is_dir()` / `file_exists()` 체크)
---
## Composer 의존성 관리
모듈/플러그인이 외부 Composer 패키지(예: `stripe/stripe-php`)를 필요로 할 때, 각 확장의 `composer.json`에 `require`로 정의하고 확장별 독립 `vendor/` 디렉토리에 설치합니다.
### 핵심 원칙
```text
중요: 루트 composer.json에 모듈/플러그인 패키지 추가 금지
✅ 결정: 각 확장의 composer.json → 확장별 vendor/ 디렉토리에 독립 설치
✅ 장점: 확장 간 의존성 충돌 방지, 삭제 시 깔끔한 정리
```
### 동작 방식
```text
모듈/플러그인 설치 시 (Phase 4.5)
↓
hasComposerDependencies() → 외부 패키지 존재 여부 확인
↓ (존재 시)
runComposerInstall() → 확장 디렉토리에서 composer install 실행
↓
modules/{name}/vendor/ 또는 plugins/{name}/vendor/ 생성
↓
updateComposerAutoload() → autoload-extensions.php에 vendor_autoloads 등록
↓
public/index.php / artisan → vendor/autoload.php를 require_once
```
### 주요 메서드
| 메서드 | 시그니처 | 설명 |
|--------|----------|------|
| `hasComposerDependencies` | `(string $type, string $dirName): bool` | 외부 패키지 의존성 존재 여부 (`php`, `ext-*` 제외) |
| `getComposerDependencies` | `(string $type, string $dirName): array` | 외부 패키지 목록 반환 |
| `runComposerInstall` | `(string $type, string $dirName, bool $noDev, ?Command $command): bool` | 확장 디렉토리에서 `composer install` 실행 |
| `detectDuplicatePackages` | `(): array` | 여러 확장에서 중복 사용되는 패키지 감지 |
| `isComposerUnchanged` | `(string $stagingPath, string $activePath): bool` | 스테이징/활성 디렉토리의 composer 변경 여부 확인 |
### Composer 의존성 변경 감지 (isComposerUnchanged)
업데이트 시 불필요한 `composer install`을 스킵하기 위해 `composer.json`과 `composer.lock`을 이중 해시 비교합니다:
```text
isComposerUnchanged(stagingPath, activePath)
↓ 활성 디렉토리 또는 vendor/ 미존재 → false (설치 필요)
↓ composer.json 한쪽 미존재 → false (변경으로 간주)
↓ md5_file(staging/composer.json) !== md5_file(active/composer.json) → false
↓ composer.lock 존재 여부 불일치 → false
↓ md5_file(staging/composer.lock) !== md5_file(active/composer.lock) → false
↓ 모두 일치 → true (스킵 가능)
```
- **이중 비교**: `composer.json`(의존성 선언) + `composer.lock`(실제 설치 버전) 모두 확인
- **false 반환 = 설치 필요**: 하나라도 변경되었으면 `composer install` 실행
- **true 반환 = 스킵 가능**: 기존 `vendor/` 디렉토리 재사용
### runComposerInstall 환경변수
웹 서버 환경에서 Composer 실행 시 시스템 환경변수가 부족하므로, `install-worker.php` 패턴과 동일하게 환경변수를 명시적으로 구성합니다.
| 환경변수 | 출처/설정값 | 용도 |
|----------|-----------|------|
| PATH, SystemRoot | `getenv()`으로 시스템에서 복사 | Composer 바이너리 탐색 |
| TEMP, TMP | 시스템에서 복사, 불가 시 `storage/temp` | 임시 파일 (Windows 특이) |
| APPDATA, LOCALAPPDATA, USERPROFILE | `getenv()`으로 시스템에서 복사 | Windows 사용자 경로 |
| COMPOSER_HOME | `storage/composer` | Composer 캐시 디렉토리 |
| HOME | `storage/composer` | Unix-style 홈 디렉토리 |
### 삭제 시 vendor 정리
`InspectsUninstallData` trait이 제공하는 메서드:
| 메서드 | 설명 |
|--------|------|
| `getVendorDirectoryInfo(string $type, string $dirName): ?array` | vendor/ 디렉토리 크기 정보 조회 (삭제 모달 표시용) |
| `deleteVendorDirectory(string $type, string $dirName): void` | vendor/ 디렉토리 및 composer.lock 삭제 |
- **삭제 시점**: `uninstallModule`/`uninstallPlugin`에서 `$deleteData === true`일 때 실행
- **실패 처리**: 삭제 실패 시 예외를 catch하고 로그만 남김 (프로세스 중단하지 않음)
---
## Artisan 커맨드
### extension:update-autoload
모듈과 플러그인의 오토로드 캐시 파일을 생성합니다.
```bash
php artisan extension:update-autoload
```
**사용 시점**:
- 모듈/플러그인 디렉토리를 수동으로 추가/삭제한 경우
- 오토로드 캐시 파일이 손상된 경우
- 개발 중 오토로드 문제 디버깅
**출력 예시**:
```bash
$ php artisan extension:update-autoload
확장 오토로드 파일을 생성합니다...
오토로드 파일이 성공적으로 생성되었습니다.
→ bootstrap/cache/autoload-extensions.php
```
### extension:composer-install
모든 모듈과 플러그인의 Composer 의존성을 일괄 설치합니다.
```bash
php artisan extension:composer-install
```
**옵션**:
- `--no-dev`: dev 의존성 제외
**사용 시점**:
- 프로젝트 초기 설정 시 모든 확장의 의존성을 한번에 설치
- 배포 환경 구성 시
**동작**:
- `module:composer-install --all`과 `plugin:composer-install --all`을 순차 호출
---
## 식별자 검증 규칙 (ValidExtensionIdentifier)
모듈/플러그인/템플릿 설치 시 `ValidExtensionIdentifier` 규칙으로 식별자 형식을 공통 검증합니다:
| 규칙 | 설명 | 예시 |
| ---------- | ---------- | ---------- |
| **하이픈 1차 구분** | 최소 2개 부분 필수 (vendor-name) | `sirsoft-board` ✅ / `sirsoftboard` ❌ |
| **언더스코어 2차 구분** | 이름 내 단어 구분 (선택적) | `sirsoft-daum_postcode` ✅ |
| **영문 소문자 + 숫자 + `_`만** | 대문자, 특수문자 불가 | `Sirsoft-Board` ❌ / `sirsoft-my@module` ❌ |
| **각 단어 첫 글자 숫자 불가** | 하이픈/언더스코어로 구분된 각 단어 기준 | `sirsoft-2shop` ❌ / `sirsoft-board2` ✅ |
| **빈 부분 불가** | 연속 하이픈/언더스코어, 양끝 하이픈/언더스코어 금지 | `sirsoft--board` ❌ / `-sirsoft-board` ❌ |
| **최대 255자** | 길이 제한 | - |
### 유효/무효 예시
```text
✅ sirsoft-board → Sirsoft\Board
✅ sirsoft-daum_postcode → Sirsoft\DaumPostcode
✅ sirsoft-board2 → Sirsoft\Board2
✅ vendor-my_module_name → Vendor\MyModuleName
❌ sirsoftboard → 하이픈 없음 (최소 2부분 필수)
❌ sirsoft-2shop → '2shop' 첫 글자 숫자
❌ Sirsoft-Board → 대문자 사용
❌ sirsoft-my@module → 특수문자 '@'
❌ sirsoft--board → 연속 하이픈 (빈 부분)
❌ sirsoft-board_ → 끝 언더스코어 (빈 단어)
```
### Artisan 커맨드에서의 검증
`module:install`, `plugin:install`, `template:install` 등에서 `ExtensionManager::validateIdentifierFormat()`을 호출하여 잘못된 식별자 입력 시 `InvalidArgumentException`을 발생시킵니다.
### 관련 파일
- `app/Rules/ValidExtensionIdentifier.php` — 검증 규칙 구현
- `ExtensionManager::validateIdentifierFormat()` — Artisan 커맨드용 래퍼
---
## 서비스 등록
`CoreServiceProvider`에서 싱글톤으로 등록됩니다.
```php
// app/Providers/CoreServiceProvider.php
public function register(): void
{
// 확장 매니저 등록 (모듈/플러그인 공통 기능)
$this->app->singleton(ExtensionManager::class, function ($app) {
return new ExtensionManager;
});
// 모듈 매니저에 주입
$this->app->singleton(ModuleManager::class, function ($app) {
return new ModuleManager($app->make(ExtensionManager::class));
});
// 플러그인 매니저에 주입
$this->app->singleton(PluginManager::class, function ($app) {
return new PluginManager($app->make(ExtensionManager::class));
});
}
```
### 의존성 관계
```
ExtensionManager (독립)
↓
ModuleManager ← ExtensionManager 주입
↓
PluginManager ← ExtensionManager 주입
```
---
## 관련 문서
- [모듈 개발 기초](module-basics.md) - 모듈 구조 및 설정
- [플러그인 개발](plugin-development.md) - 플러그인 구조 및 설정
- [모듈 Artisan 커맨드](module-commands.md) - 모듈 관련 커맨드
- [확장 업데이트 시스템](extension-update-system.md) - _bundled/_pending 및 업데이트
- [인덱스](index.md) - 확장 시스템 전체 문서 목록
+746
View File
@@ -0,0 +1,746 @@
# 확장 업데이트 시스템 (Extension Update System)
> 모듈, 플러그인, 템플릿의 버전 업데이트 감지, 실행, 롤백을 관리하는 시스템
## TL;DR (5초 요약)
```text
1. 업데이트 감지 우선순위: GitHub > _bundled (2단계, _pending 미참여)
2. _bundled = Git 추적 선탑재 소스, _pending = 설치 시 임시 스테이징만
3. 상태 가드: ExtensionStatusGuard.assertNotInProgress(ExtensionStatus, identifier)
4. 업그레이드 콜백: upgrades/ 디렉토리에 Upgrade_X_Y_Z.php (UpgradeStepInterface 구현)
5. 역할/권한/메뉴 동기화: user_overrides로 사용자 커스터마이징 보존 (개별 식별자 보호)
```
---
## 목차
1. [_bundled vs _pending 디렉토리](#1-_bundled-vs-_pending-디렉토리)
2. [업데이트 감지](#2-업데이트-감지)
3. [업데이트 실행 흐름](#3-업데이트-실행-흐름)
4. [ExtensionStatusGuard](#4-extensionstatusguard)
5. [ExtensionBackupHelper](#5-extensionbackuphelper)
6. [ExtensionPendingHelper](#6-extensionpendinghelper)
7. [UpgradeStepInterface + UpgradeContext](#7-upgradestepinterface--upgradecontext)
8. [번들 디렉토리 개발 워크플로우](#8-번들-디렉토리-개발-워크플로우-critical---mandatory)
9. [개발자 버전 업데이트 가이드](#9-개발자-버전-업데이트-가이드)
10. [템플릿 레이아웃 충돌 전략](#10-템플릿-레이아웃-충돌-전략)
11. [Artisan 커맨드](#11-artisan-커맨드)
12. [API 엔드포인트](#12-api-엔드포인트)
13. [역할/권한/메뉴 동기화](#13-역할권한메뉴-동기화)
14. [SettingsMigrator](#14-settingsmigrator)
15. [큐 워커 재시작 + 스케줄 등록](#15-큐-워커-재시작--스케줄-등록)
---
## 1. _bundled vs _pending 디렉토리
| 속성 | `_bundled/` | `_pending/` |
|------|------------|-------------|
| **용도** | 선탑재 확장 소스 (배포 포함) | 외부 다운로드/업로드 스테이징 |
| **Git 추적** | O (추적됨) | X (`.gitignore` 제외) |
| **수명** | 항상 존재 | 설치 완료 후 삭제 가능 |
| **업데이트 감지** | **참여** (GitHub 다음 우선순위) | **미참여** |
| **사용 시점** | 설치 + 업데이트 소스 | 설치 시 스테이징만 |
| **디렉토리 구조** | `modules/_bundled/vendor-module/` | `modules/_pending/vendor-module/` |
### 디렉토리 자동 제외
`_`로 시작하는 디렉토리는 ExtensionManager에서 활성 확장으로 인식하지 않습니다:
```php
// str_starts_with($name, '_') → skip
// _bundled, _pending 모두 자동 제외
```
---
## 2. 업데이트 감지
### 우선순위 (2단계)
```
1. GitHub (github_url이 설정된 경우) → GitHub API로 최신 버전 조회
2. _bundled (선탑재 소스) → _bundled/{identifier}/manifest.json에서 버전 비교
```
> **주의**: `_pending` 디렉토리는 업데이트 감지에 **참여하지 않습니다**.
### 감지 결과
```php
[
'update_available' => true,
'update_source' => 'github' | 'bundled', // pending 없음
'latest_version' => '1.2.0',
'current_version' => '1.0.0',
]
```
### check-updates API 흐름
1. Service 레이어에서 훅 발행: `core.{type}.before_check_updates`
2. Manager의 `checkAll{Type}ForUpdates()` 호출
3. 각 확장별 `check{Type}Update($identifier)` 실행
4. DB에 `update_available`, `latest_version`, `update_source`, `github_changelog_url` 갱신
5. 훅 발행: `core.{type}.after_check_updates`
### GitHub 아카이브 다운로드 및 해석
GitHub 소스 업데이트 시 아카이브 URL 해석 → 다운로드 → 압축 해제 과정을 거칩니다:
**v접두사 자동 감지** (`resolveGithubArchiveUrl`):
```text
1. "v{version}" 태그로 HEAD 요청 시도 (예: v1.2.0)
2. 실패 시 "{version}" 태그로 HEAD 요청 시도 (예: 1.2.0)
3. HTTP 200/302 → 유효한 URL 반환
4. 모두 실패 → null 반환 (업데이트 불가)
```
**아카이브 추출 전략** (2단계 폴백):
| 순서 | 방식 | 조건 |
| ---------- | ---------- | ---------- |
| 1 | `ZipArchive` (PHP zip 확장) | `class_exists(ZipArchive::class)` |
| 2 | `unzip` CLI 명령어 | ZipArchive 미사용 시 폴백 |
**GitHub 아카이브 디렉토리 구조**: GitHub zipball은 `owner-repo-hash/` 형태의 루트 디렉토리를 포함합니다. `ZipInstallHelper::findAndValidateManifest()`가 1단계 하위 디렉토리까지 자동 검색하여 매니페스트 파일을 찾습니다.
---
## 3. 업데이트 실행 흐름
### 모듈/플러그인 업데이트 (10단계)
```
1. [가드] ExtensionStatusGuard::assertNotInProgress()
2. [백업] ExtensionBackupHelper::createBackup()
3. [상태] status → Updating
4. [파일] 소스에서 활성 디렉토리로 복사
- github: 다운로드 후 복사
- bundled: ExtensionPendingHelper::copyToActive()
5. [마이그레이션] runMigrations()
6. [DB 트랜잭션] 버전/메타데이터 갱신
- Roles, Permissions, Menus 동기화 (→ [13. 역할/권한/메뉴 동기화](#13-역할권한메뉴-동기화))
7. [레이아웃] 활성 상태였으면 레이아웃 갱신
- registerModuleLayouts() + registerLayoutExtensions() + refreshModuleLayouts()
8. [오토로드] Composer autoload 갱신
9. [업그레이드] runUpgradeSteps($module, $fromVersion, $toVersion)
10. [마무리] 이전 상태 복원 + 백업 삭제 + 캐시 무효화
```
### 템플릿 업데이트 (차이점)
- **마이그레이션**: 없음 (템플릿은 DB 스키마 미사용)
- **업그레이드 스텝**: 없음
- **레이아웃 전략**: `layout_strategy` 파라미터로 충돌 처리 (→ [10. 레이아웃 충돌 전략](#10-템플릿-레이아웃-충돌-전략))
- **Roles/Permissions/Menus**: 없음
### 에러 발생 시
```
1. ExtensionBackupHelper::restoreFromBackup() → 파일 원복
2. status → 이전 상태 복원
3. 에러 로깅 (upgrade 채널)
```
---
## 4. ExtensionStatusGuard
> 파일: `app/Extension/Helpers/ExtensionStatusGuard.php`
### 시그니처
```php
public static function assertNotInProgress(ExtensionStatus $status, string $identifier): void
```
### 차단 매트릭스
| 현재 상태 | 설치 | 삭제 | 활성화 | 비활성화 | 업데이트 |
|----------|------|------|--------|---------|---------|
| Active | - | O | - | O | O |
| Inactive | - | O | O | - | O |
| **Installing** | **차단** | **차단** | **차단** | **차단** | **차단** |
| **Uninstalling** | **차단** | **차단** | **차단** | **차단** | **차단** |
| **Updating** | **차단** | **차단** | **차단** | **차단** | **차단** |
| Uninstalled | O | - | - | - | - |
- `Installing`, `Uninstalling`, `Updating` 상태에서는 모든 작업이 `\RuntimeException`으로 차단됩니다.
---
## 5. ExtensionBackupHelper
> 파일: `app/Extension/Helpers/ExtensionBackupHelper.php`
### 메서드
```php
// 백업 생성 → storage/app/extension_backups/{type}/{identifier}_{timestamp}/
public static function createBackup(string $type, string $identifier): string
// 백업에서 복원 (copyToActive의 원자적 교체 사용)
public static function restoreFromBackup(string $type, string $identifier, string $backupPath): void
// 백업 삭제 (경로 미존재 시 무시)
public static function deleteBackup(string $backupPath): void
```
- `$type`: `'modules'`, `'plugins'`, `'templates'`
- 타임스탬프 형식: `Ymd_His` (예: `20260224_143052`)
- 파일 작업: `Illuminate\Support\Facades\File` 사용
---
## 6. ExtensionPendingHelper
> 파일: `app/Extension/Helpers/ExtensionPendingHelper.php`
### 메서드 (8개)
```php
// _pending 확장 목록 로드
public static function loadPendingExtensions(string $basePath, string $manifestName): array
// _bundled 확장 목록 로드
public static function loadBundledExtensions(string $basePath, string $manifestName): array
// _pending/_bundled → 활성 디렉토리로 원자적 교체 (rename→rename→delete 패턴)
public static function copyToActive(string $sourcePath, string $targetPath): void
// 확장 디렉토리 삭제 (경로 미존재 시 무시)
public static function deleteExtensionDirectory(string $basePath, string $identifier): void
// _pending 디렉토리에 존재 여부
public static function isPending(string $basePath, string $identifier): bool
// _bundled 디렉토리에 존재 여부
public static function isBundled(string $basePath, string $identifier): bool
// _pending 경로 반환
public static function getPendingPath(string $basePath, string $identifier): string
// _bundled 경로 반환
public static function getBundledPath(string $basePath, string $identifier): string
```
- `$basePath`: `base_path('modules')`, `base_path('plugins')`, `base_path('templates')`
- `$manifestName`: `'module.json'`, `'plugin.json'`, `'template.json'`
### copyToActive 원자적 교체 패턴
`copyToActive()`는 기존 대상 디렉토리가 있을 때 **rename→rename→delete** 패턴으로 원자적 교체를 수행합니다.
임시 디렉토리(`_updating_*`, `_old_*`)는 **`_pending/` 하위**에 생성되므로, 잔존 시에도 오토로드에 포함되지 않습니다:
```text
1. source → _pending/{id}_updating_{uid} (File::copyDirectory) # _pending/ 하위 임시 경로에 복사
2. target → _pending/{id}_old_{uid} (File::moveDirectory) # 기존을 _pending/ 하위 _old로 rename
3. _pending/{id}_updating_{uid} → target (File::moveDirectory) # 임시를 활성으로 rename
4. _pending/{id}_old_{uid} 삭제 (File::deleteDirectory) # 이전 버전 삭제 (실패해도 무해)
```
| 실패 시점 | 결과 |
| --------- | ---- |
| 1단계 실패 (복사) | 기존 디렉토리 **온전히 보존**, `_pending/` 내 임시 디렉토리 정리 후 예외 |
| 2단계 실패 (rename) | 기존 디렉토리 **온전히 보존**, `_pending/` 내 임시만 정리 |
| 3단계 실패 (rename) | `_pending/` 내 _old를 원래 위치로 **롤백**, 예외 |
> **Windows 참고**: `deleteDirectory` 직후 같은 이름으로 `rename`이 실패하는 타이밍 이슈가 있어, delete→copy 대신 rename→rename→delete 패턴을 사용합니다.
> **오토로드 안전성**: 임시 디렉토리가 `_pending/` 하위에 생성되므로, IDE 잠금 등으로 잔존하더라도 `str_starts_with($name, '_')` 필터에 의해 오토로드에서 자동 제외됩니다.
이 메서드는 다음 위치에서 공통으로 사용됩니다:
- `ExtensionBackupHelper::restoreFromBackup()` — 백업 복원
- `ModuleManager::downloadModuleUpdate()` — GitHub 다운로드 교체
- `PluginManager::downloadPluginUpdate()` — 동일
- `TemplateManager::downloadTemplateUpdate()` — 동일
---
## 7. UpgradeStepInterface + UpgradeContext
### 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')` 필수**
### 업그레이드 스텝 작성 예시
```php
// modules/vendor-module/upgrades/Upgrade_1_1_0.php
namespace Modules\Vendor\Module\Upgrades;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\UpgradeContext;
class Upgrade_1_1_0 implements UpgradeStepInterface
{
public function run(UpgradeContext $context): void
{
$context->logger->info("Upgrading from {$context->fromVersion} to {$context->toVersion}");
// 데이터 마이그레이션 등 버전 특화 작업
}
}
```
### 정적 메뉴/권한 제거 시 cleanup 사용 예시
확장이 새 버전에서 기존 정적 메뉴/권한을 제거해야 하는 경우, UpgradeStep에서 cleanup helper를 명시적으로 호출합니다.
> **주의**: `cleanupStaleMenus()`/`cleanupStalePermissions()`는 정적 정의 기반으로만 판단하므로, 확장이 런타임에 동적으로 생성한 메뉴/권한도 삭제됩니다. 동적 메뉴/권한이 있는 확장에서는 삭제 대상을 직접 특정하는 것이 안전합니다.
```php
// upgrades/Upgrade_2_0_0.php — 정적 메뉴 정리 예시
use App\Extension\Helpers\ExtensionMenuSyncHelper;
use App\Enums\ExtensionOwnerType;
class Upgrade_2_0_0 implements UpgradeStepInterface
{
public function run(UpgradeContext $context): void
{
$menuHelper = app(ExtensionMenuSyncHelper::class);
$menuHelper->cleanupStaleMenus(
ExtensionOwnerType::Module,
'vendor-module',
['menu-slug-1', 'menu-slug-2'], // 유지할 slug 목록
);
}
}
```
### 자동 발견 규칙
- 디렉토리: `{extensionPath}/upgrades/`
- 파일 패턴: `Upgrade_X_Y_Z.php` (언더스코어 → 점으로 변환: `1_1_0` → `1.1.0`)
- 실행 순서: `fromVersion < stepVersion <= toVersion` 범위의 스텝만 자연 정렬 순 실행
---
## 8. 번들 디렉토리 개발 워크플로우
### 핵심 원칙
```text
필수: 확장(모듈/플러그인/템플릿) 수정/개발은 _bundled 디렉토리에서만 작업
필수: _bundled 작업 완료 후 반영/검증은 업데이트 프로세스(update 커맨드) 사용
이유: 활성 디렉토리 직접 수정 시 _bundled와 불일치 → 업데이트 시 변경 유실
이유: 업데이트 프로세스를 통해야 마이그레이션, 권한/메뉴 동기화, 레이아웃 갱신 등이 정상 수행됨
```
### 개발 워크플로우 (필수 절차)
```text
┌─────────────────────────────────────────────────────────────────┐
│ 1. _bundled 디렉토리에서 코드 수정/개발 │
│ 예: modules/_bundled/sirsoft-ecommerce/src/Services/... │
│ │
│ 2. manifest 버전 올리기 (module.json / plugin.json / template.json) │
│ 예: "version": "1.0.0" → "1.1.0" │
│ │
│ 3. 업그레이드 스텝 작성 (조건부 - DB/설정 변경 시) │
│ 예: upgrades/Upgrade_1_1_0.php │
│ │
│ 4. 업데이트 커맨드로 활성 디렉토리에 반영 │
│ php artisan module:update sirsoft-ecommerce │
│ php artisan plugin:update sirsoft-payment │
│ php artisan template:update sirsoft-admin_basic │
│ │
│ 5. 업데이트 결과 검증 (테스트 실행) │
│ php artisan test --filter=관련테스트 │
│ powershell -Command "npm run test:run -- 관련테스트" │
└─────────────────────────────────────────────────────────────────┘
```
### 왜 활성 디렉토리 직접 수정이 금지되는가?
| 문제 | 설명 |
|------|------|
| **변경 유실** | 다음 업데이트 시 _bundled 소스로 덮어쓰기되어 활성 디렉토리의 직접 수정 사항이 사라짐 |
| **동기화 누락** | 권한/역할/메뉴 동기화, 레이아웃 갱신, 마이그레이션 실행 등 업데이트 프로세스의 후처리가 수행되지 않음 |
| **Git 추적 불가** | 활성 디렉토리는 .gitignore 대상이므로 변경 사항이 Git에 기록되지 않음 |
| **환경 불일치** | _bundled(Git 추적)와 활성 디렉토리(Git 미추적)가 불일치하여 다른 환경에서 재현 불가 |
| **업데이트 감지 불가** | 활성 디렉토리만 수정하고 _bundled를 미갱신하면 check-updates에서 변경을 감지하지 못함 |
### 확장 타입별 업데이트 커맨드
| 확장 타입 | 업데이트 확인 | 업데이트 실행 | 강제 재설치 |
| -------- | ----------- | ----------- | ---------- |
| 모듈 | `php artisan module:check-updates sirsoft-ecommerce` | `php artisan module:update sirsoft-ecommerce` | `php artisan module:update sirsoft-ecommerce --force` |
| 플러그인 | `php artisan plugin:check-updates sirsoft-payment` | `php artisan plugin:update sirsoft-payment` | `php artisan plugin:update sirsoft-payment --force` |
| 템플릿 | `php artisan template:check-updates sirsoft-admin_basic` | `php artisan template:update sirsoft-admin_basic` | `php artisan template:update sirsoft-admin_basic --force` |
### 예외: 초기 개발 (아직 _bundled에 미등록)
신규 확장을 처음 개발할 때는 활성 디렉토리에서 직접 작업할 수 있습니다. 단, **최초 개발 완료 후 _bundled에 반영하는 시점부터** 이 규칙이 적용됩니다.
```text
허용: 신규 확장 초기 개발 시 활성 디렉토리에서 직접 작업
전환점: _bundled에 최초 반영한 이후부터는 반드시 _bundled에서만 작업
전환 후: 활성 디렉토리 직접 수정 금지 → 업데이트 프로세스만 사용
```
---
## 9. 개발자 버전 업데이트 가이드
### 코드 변경 시 버전/업그레이드 필수 규칙
```text
필수: 확장(모듈/플러그인/템플릿)의 코드를 변경한 경우 아래 절차를 수행해야 합니다.
버전 변경 없이 코드만 수정하면, 이미 설치된 환경에서 업데이트가 감지되지 않습니다.
```
#### 필수 체크리스트
| # | 항목 | 모듈 | 플러그인 | 템플릿 |
|---|------|------|---------|--------|
| 1 | manifest 버전 올리기 (`module.json` / `plugin.json` / `template.json`) | ✅ 필수 | ✅ 필수 | ✅ 필수 |
| 2 | `_bundled` 디렉토리 동기화 (활성 디렉토리와 동일하게) | ✅ 필수 | ✅ 필수 | ✅ 필수 |
| 3 | 업그레이드 스텝 작성 (`upgrades/Upgrade_X_Y_Z.php`) | 조건부 | 조건부 | 해당 없음 |
| 4 | DB 마이그레이션 추가 (`database/migrations/`) | 조건부 | 조건부 | 해당 없음 |
#### 업그레이드 스텝이 필요한 경우 (모듈/플러그인만)
다음 중 하나라도 해당하면 `upgrades/Upgrade_X_Y_Z.php`를 작성해야 합니다:
| 변경 유형 | 업그레이드 스텝 필요 | 예시 |
|----------|-------------------|------|
| DB 스키마 변경 | ✅ (+ 마이그레이션) | 컬럼 추가/삭제, 테이블 구조 변경 |
| 환경설정 구조 변경 | ✅ (SettingsMigrator 사용) | 설정 키 이름 변경, 새 카테고리 추가 |
| 기존 데이터 마이그레이션 | ✅ | 데이터 형식 변환, 기본값 채우기 |
| 권한/역할/메뉴 추가·수정 | ❌ (자동 동기화) | 새 권한 추가, 메뉴 순서 변경 |
| 정적 권한/메뉴 제거 | ✅ (cleanup 명시 호출) | 기존 메뉴/권한 삭제 |
| 레이아웃 JSON 변경 | ❌ (자동 갱신) | 레이아웃 UI 수정, 새 레이아웃 추가 |
| PHP 코드만 변경 (API 호환) | ❌ | 버그 수정, 성능 개선 |
#### 버전 올리기 않아도 되는 경우
- `_bundled` 디렉토리에 아직 반영되지 않은 개발 중 변경 (활성 디렉토리에서만 작업)
- 테스트 파일만 변경
- 규정 문서만 변경
### 새 버전 배포 절차
1. **manifest 버전 수정**: `module.json` / `plugin.json` / `template.json`의 `version` 필드 변경
2. **업그레이드 스텝 작성** (필요 시): `upgrades/Upgrade_X_Y_Z.php` 생성
3. **_bundled 업데이트**: Git 저장소의 `_bundled/{identifier}/` 디렉토리 갱신
4. **GitHub 릴리스** (선택): `github_url` 설정 시 GitHub releases로 자동 감지
### manifest 수정 항목
```json
{
"version": "1.2.0",
"github_changelog_url": "https://github.com/vendor/module/releases/tag/engine-v1.2.0"
}
```
---
## 10. 템플릿 레이아웃 충돌 전략
템플릿 업데이트 시 관리자가 수정한 레이아웃이 있으면 충돌이 발생합니다.
### 사전 확인 API
```
GET /api/admin/templates/{templateName}/check-modified-layouts
```
응답:
```json
{
"has_modified": true,
"modified_layouts": [
{ "id": 1, "name": "dashboard", "updated_at": "2026-02-24T10:00:00Z" }
]
}
```
### 충돌 해결 전략
| 전략 | 동작 |
|------|------|
| `apply_new` (기본값) | 새 버전의 레이아웃으로 덮어쓰기 (관리자 수정 사항 유실) |
| `keep_current` | 기존 레이아웃 유지 (새 버전 레이아웃 미적용) |
업데이트 API에 `layout_strategy` 파라미터로 전달:
```
POST /api/admin/templates/{templateName}/update
Body: { "layout_strategy": "apply_new" }
```
---
## 11. Artisan 커맨드
| 커맨드 | 설명 |
|--------|------|
| `module:check-updates [identifier?]` | 모듈 업데이트 확인 (전체 또는 단일) |
| `module:update [identifier] [--force]` | 모듈 업데이트 실행 |
| `plugin:check-updates [identifier?]` | 플러그인 업데이트 확인 (전체 또는 단일) |
| `plugin:update [identifier] [--force]` | 플러그인 업데이트 실행 |
| `template:check-updates [identifier?]` | 템플릿 업데이트 확인 (전체 또는 단일) |
| `template:update [identifier] [--layout-strategy=overwrite] [--force]` | 템플릿 업데이트 실행 |
> 단일 `check-updates`는 `checkXxxUpdate()` 호출 후 커맨드에서 DB 갱신 (`updateByIdentifier()`)
> 템플릿 `update`만 `--layout-strategy` 옵션 지원 (`overwrite` | `keep`)
> `--force`: 버전 비교를 건너뛰고 강제 재설치 (파일 손상, 수동 수정 복원 시 사용)
---
## 12. API 엔드포인트
### 모듈
| 메서드 | 경로 | 권한 | 설명 |
|--------|------|------|------|
| POST | `/api/admin/modules/check-updates` | `core.modules.install` | 모듈 업데이트 일괄 확인 |
| POST | `/api/admin/modules/{moduleName}/update` | `core.modules.install` | 모듈 업데이트 실행 |
### 플러그인
| 메서드 | 경로 | 권한 | 설명 |
|--------|------|------|------|
| POST | `/api/admin/plugins/check-updates` | `core.plugins.install` | 플러그인 업데이트 일괄 확인 |
| POST | `/api/admin/plugins/{pluginName}/update` | `core.plugins.install` | 플러그인 업데이트 실행 |
### 템플릿
| 메서드 | 경로 | 권한 | 설명 |
|--------|------|------|------|
| POST | `/api/admin/templates/check-updates` | `core.templates.install` | 템플릿 업데이트 일괄 확인 |
| GET | `/api/admin/templates/{templateName}/check-modified-layouts` | `core.templates.read` | 수정된 레이아웃 확인 |
| POST | `/api/admin/templates/{templateName}/update` | `core.templates.install` | 템플릿 업데이트 실행 |
### 훅 (Hook)
| 훅 이름 | 시점 |
|---------|------|
| `core.modules.before_check_updates` | 모듈 업데이트 확인 전 |
| `core.modules.after_check_updates` | 모듈 업데이트 확인 후 |
| `core.modules.before_update` | 모듈 업데이트 실행 전 |
| `core.modules.after_update` | 모듈 업데이트 실행 후 |
| `core.plugins.before_check_updates` | 플러그인 업데이트 확인 전 |
| `core.plugins.after_check_updates` | 플러그인 업데이트 확인 후 |
| `core.plugins.before_update` | 플러그인 업데이트 실행 전 |
| `core.plugins.after_update` | 플러그인 업데이트 실행 후 |
| `core.templates.before_check_updates` | 템플릿 업데이트 확인 전 |
| `core.templates.after_check_updates` | 템플릿 업데이트 확인 후 |
| `core.templates.before_version_update` | 템플릿 업데이트 실행 전 |
| `core.templates.after_version_update` | 템플릿 업데이트 실행 후 |
---
## 13. 역할/권한/메뉴 동기화
> 파일: `app/Extension/Helpers/ExtensionRoleSyncHelper.php`, `app/Extension/Helpers/ExtensionMenuSyncHelper.php`
업데이트 실행 흐름 6단계에서 Roles, Permissions, Menus를 동기화할 때, 사용자 커스터마이징을 보존하면서 안전하게 갱신합니다.
### user_overrides 패턴
각 모델(Role, Menu)에 `user_overrides` JSON 컬럼이 존재합니다. 유저가 수정한 필드명 또는 개별 식별자를 기록하고, 확장 재설치/업데이트 시 **기록된 항목만 보호**합니다.
```text
유저 수정 시: Listener가 user_overrides에 변경 내용 자동 기록
- 필드 변경 (name, icon 등) → 필드명 기록: ["name", "icon"]
- 권한 변경 → 개별 권한 식별자 기록: ["sirsoft-board.boards.delete"]
- 역할 변경 → 개별 역할 식별자 기록: ["editor"]
- 순서 변경 → "order" 기록: ["order"]
확장 업데이트 시: user_overrides에 기록된 항목만 보호, 나머지 정상 갱신
```
### 역할/권한 동기화 (ExtensionRoleSyncHelper)
- **syncRole()**: `user_overrides`에 기록된 필드(name, description)만 건너뛰고 나머지 갱신
- **syncPermission()**: 항상 확장 정의값으로 덮어쓰기 (Permission은 user_overrides 없음)
- **syncRolePermissions()**: `user_overrides`에 기록된 **개별 권한 식별자**만 보호, 나머지 DB 기반 diff로 attach/detach
- **cleanupStalePermissions()**: 확장에서 제거된 권한 삭제 + 역할 연결 해제 (**자동 호출 폐기 #135** — UpgradeStep에서 명시적 호출 전용)
### 역할-권한 할당 동기화 (syncAllRoleAssignments)
```text
주의: DB 기반 diff + 개별 권한 식별자 보호
유저가 admin에서 boards.delete 해제 → user_overrides = ["sirsoft-board.boards.delete"]
확장 v1.1 업데이트:
→ DB에서 현재 확장 권한 조회
→ user_overrides에서 권한 식별자만 필터 (필드명 "name" 등 제외)
→ 보호된 권한(boards.delete)은 attach/detach 계산에서 제외
→ 나머지 권한은 정의 기준으로 정상 동기화
```
| 시나리오 | 동작 |
| -------- | ---- |
| 최초 설치 (user_overrides=[]) | 정의된 모든 권한 attach |
| 업데이트 (보호 권한 있음) | 보호 권한 제외, 나머지 diff 동기화 |
| 확장이 새 권한 추가 | 비보호 → attach, 보호 → 건너뜀 |
| 확장에서 권한 제거 | 비보호 → detach, 보호 → 건너뜀 |
| 유저 수동 추가 할당 (비확장 권한) | 영향 없음 (확장 권한만 대상) |
### 메뉴 동기화 (ExtensionMenuSyncHelper)
- **비교 필드**: `user_overrides`에 기록된 필드만 건너뜀 (name, icon, order, url 중)
- **항상 확장 정의값**: parent_id, is_active (사용자 보존 대상 아님)
- **syncMenuRecursive()**: 재귀 구조 처리 + 다국어 name 역호환
- **cleanupStaleMenus()**: 자식 포함 cascade 삭제 (**자동 호출 폐기 #135** — UpgradeStep에서 명시적 호출 전용)
- **메뉴-역할 할당**: `user_overrides`에 기록된 **개별 역할 식별자**만 보호
```text
예시: 유저가 name과 editor 역할을 변경
→ user_overrides = ["name", "editor"]
모듈 v1.1 업데이트:
→ name: user_overrides에 있음 → 보존
→ order: user_overrides에 없음 → 새 값 반영
→ icon: user_overrides에 없음 → 새 값 반영
→ 역할 editor: 보호 → 유저 설정 유지
→ 역할 admin: 비보호 → 정상 동기화
```
### user_overrides 기록 리스너
| 리스너 | 구독 훅 | 기록 내용 |
| ------ | ------- | --------- |
| `RoleUserOverridesListener` | `core.role.before_update` | 변경된 필드명 (name, description) |
| `RoleUserOverridesListener` | `core.role.after_sync_permissions` | 변경된 개별 권한 식별자 |
| `MenuUserOverridesListener` | `core.menu.before_update` | 변경된 필드명 (name, icon, order, url) |
| `MenuUserOverridesListener` | `core.menu.after_update_order` | 순서 변경된 메뉴에 "order" |
| `MenuUserOverridesListener` | `core.menu.after_sync_roles` | 변경된 개별 역할 식별자 |
---
## 14. SettingsMigrator
> 파일: `app/Extension/Helpers/SettingsMigrator.php`
UpgradeStep 내에서 환경설정 파일을 안전하게 마이그레이션하는 유틸리티 클래스.
### 사용법
```php
class Upgrade_1_3_0 implements UpgradeStepInterface
{
public function run(UpgradeContext $context): void
{
$result = SettingsMigrator::forModule('sirsoft-ecommerce')
->addField('shipping.tracking_enabled', false)
->renameField('order_settings.auto_cancel_days', 'order_settings.pending_cancel_days')
->removeField('seo.deprecated_field')
->addCategory('notifications', ['email_enabled' => true])
->apply();
$context->logger->info('Settings migrated', $result);
}
}
```
### 오퍼레이션
| 메서드 | 동작 |
|--------|------|
| `addField(path, default)` | 새 필드 추가 (이미 존재하면 **스킵** — 사용자 값 보존) |
| `renameField(old, new)` | 필드 이름 변경 (이전 키 값을 새 키로 이동) |
| `removeField(path)` | 필드 제거 (존재하지 않으면 no-op) |
| `transformField(path, callable)` | 값 변환 (존재하지 않으면 스킵) |
| `addCategory(category, defaults)` | 새 카테고리 파일 생성 (모듈 전용) |
| `apply()` | 모든 변환 실행, `['applied' => int, 'skipped' => int, 'errors' => []]` 반환 |
### 경로 규칙 (dot notation)
- 모듈: `'category.field'` → `storage/app/modules/{id}/settings/{category}.json` 내 `field` 키
- 플러그인: `'field'` → `storage/app/plugins/{id}/settings/setting.json` 내 `field` 키
---
## 15. 큐 워커 재시작 + 스케줄 등록
### 큐 워커 재시작
> 파일: `app/Listeners/ExtensionUpdateQueueListener.php`
확장 업데이트 성공 시 `Artisan::call('queue:restart')` 자동 실행. 코드 변경 후 큐 워커가 이전 코드로 실행되는 문제를 방지합니다.
- 구독 훅: `core.modules.after_update`, `core.plugins.after_update` (priority 100)
- 실패 시: warning 로그만 기록 (예외 전파 안 함)
- 자동 등록: `CoreServiceProvider::registerCoreHookListeners()` 스캔
### 확장 스케줄 등록
> 파일: `routes/console.php`
활성 모듈/플러그인의 `getSchedules()` 메서드를 읽어 Laravel 스케줄러에 자동 등록합니다.
```php
// module.php에서 정의
public function getSchedules(): array
{
return [
[
'command' => 'sirsoft-ecommerce:sync-stock',
'schedule' => 'hourly', // 또는 cron: '*/30 * * * *'
'description' => '재고 동기화',
'enabled_config' => 'sirsoft-ecommerce.stock.auto_sync',
],
];
}
```
- cron expression vs 메서드명 자동 분기
- `enabled_config`: 확장 설정값으로 조건부 활성화
---
## 참고 파일 위치
| 파일 | 경로 |
|------|------|
| ExtensionStatusGuard | `app/Extension/Helpers/ExtensionStatusGuard.php` |
| ExtensionBackupHelper | `app/Extension/Helpers/ExtensionBackupHelper.php` |
| ExtensionPendingHelper | `app/Extension/Helpers/ExtensionPendingHelper.php` |
| ExtensionRoleSyncHelper | `app/Extension/Helpers/ExtensionRoleSyncHelper.php` |
| ExtensionMenuSyncHelper | `app/Extension/Helpers/ExtensionMenuSyncHelper.php` |
| SettingsMigrator | `app/Extension/Helpers/SettingsMigrator.php` |
| ExtensionUpdateQueueListener | `app/Listeners/ExtensionUpdateQueueListener.php` |
| UpgradeStepInterface | `app/Contracts/Extension/UpgradeStepInterface.php` |
| UpgradeContext | `app/Extension/UpgradeContext.php` |
| ExtensionStatus | `app/Enums/ExtensionStatus.php` |
| ModuleManager | `app/Extension/ModuleManager.php` |
| PluginManager | `app/Extension/PluginManager.php` |
| TemplateManager | `app/Extension/TemplateManager.php` |
| logging.php (upgrade 채널) | `config/logging.php` |
+885
View File
@@ -0,0 +1,885 @@
# 훅 시스템 (Hook System)
> G7의 훅 시스템은 WordPress 스타일로 구현되어 코어 수정 없이 비즈니스 로직을 확장할 수 있습니다.
---
## TL;DR (5초 요약)
```text
1. Action 훅: doAction() - 부가 작업 (로그, 알림, 캐시)
2. Filter 훅: applyFilters() - 데이터 변형 (type => 'filter' 필수!)
3. 네이밍: [vendor-module].[entity].[action]_[timing]
4. 우선순위: 1-5(높음), 10(기본), 15+(낮음)
5. Service 패턴: before_* → filter_* → 로직 → after_*
```
---
## 목차
- [개요](#개요)
- [훅 타입](#훅-타입)
- [훅 네이밍 규칙](#훅-네이밍-규칙)
- [리스너 구현](#리스너-구현)
- [코어 리스너 자동 발견](#코어-리스너-자동-발견)
- [우선순위 가이드라인](#우선순위-가이드라인)
- [모듈에 리스너 등록](#모듈에-리스너-등록)
- [Service에서 훅 사용 패턴](#service에서-훅-사용-패턴)
- [필터 훅 리스너 예시](#필터-훅-리스너-예시)
- [훅 권한 시스템](#훅-권한-시스템)
- [관련 문서](#관련-문서)
---
## 개요
G7의 훅 시스템은 WordPress 스타일로 구현되어 코어 수정 없이 비즈니스 로직을 확장할 수 있습니다.
**핵심 파일 위치**: `app/Extension/HookManager.php`
---
## 훅 타입
### 1. Action Hooks (액션 훅)
**목적**: 특정 시점에 부가 작업 실행
**사용 예시**:
- 이메일 발송
- 활동 로그 기록 (→ [활동 로그 시스템](../backend/activity-log.md) 참조)
- 캐시 무효화
- 알림 전송
**패턴**:
```php
// Service에서 훅 실행
HookManager::doAction('sirsoft-ecommerce.product.after_create', $product, $data);
```
### 2. Filter Hooks (필터 훅)
**목적**: 데이터 변형 및 가공
**사용 예시**:
- 가격 계산
- 데이터 포맷 변경
- 권한 확인
**패턴**:
```php
// Service에서 필터 적용
$finalPrice = HookManager::applyFilters('sirsoft-ecommerce.product.calculate_price', $basePrice, $product);
```
---
## 훅 네이밍 규칙
### 표준 패턴
```text
[vendor-module].[entity].[action]_[timing]
```
### 타이밍 접미사
| 접미사 | 설명 |
| ---------- | ------------------ |
| `before_*` | 작업 실행 전 |
| `after_*` | 작업 실행 후 |
| `on_*` | 특정 이벤트 발생 시 |
| `filter_*` | 데이터 변형용 필터 |
### 예시
```text
# 생성/수정/삭제 (변경 작업)
sirsoft-ecommerce.product.before_create
sirsoft-ecommerce.product.after_create
sirsoft-ecommerce.product.after_update
sirsoft-ecommerce.product.filter_create_data
# 조회 작업
sirsoft-ecommerce.product.before_list
sirsoft-ecommerce.product.after_list
sirsoft-ecommerce.product.filter_list_query
sirsoft-ecommerce.product.filter_list_result
sirsoft-ecommerce.product.before_show
sirsoft-ecommerce.product.after_show
sirsoft-ecommerce.product.filter_show_result
# 이벤트/기타
sirsoft-ecommerce.order.on_payment_success
sirsoft-ecommerce.product.calculate_price
# 코어 훅
core.attachment.download
core.attachment.update
core.attachment.delete
# FormRequest Validation Rules 훅 (Filter)
core.user.create_validation_rules
core.user.update_validation_rules
core.role.store_validation_rules
core.role.update_validation_rules
core.permission.store_validation_rules
core.permission.update_validation_rules
core.menu.store_validation_rules
core.menu.update_validation_rules
# Layout Extension 훅
core.layout_extension.before_apply
core.layout_extension.after_apply
# SEO 렌더링 훅 (Filter)
core.seo.filter_context
core.seo.filter_meta
core.seo.filter_view_data
```
---
## 리스너 구현
### HookListenerInterface 사용
```php
<?php
namespace Modules\Sirsoft\Ecommerce\Listeners;
use App\Contracts\Extension\HookListenerInterface;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class ProductCacheInvalidationListener implements HookListenerInterface
{
/**
* 구독할 훅 목록 반환
*
* @return array
*/
public static function getSubscribedHooks(): array
{
return [
// Action 훅: type 생략 시 기본값 'action'
'sirsoft-ecommerce.product.after_create' => ['method' => 'handleProductChange', 'priority' => 10],
'sirsoft-ecommerce.product.after_update' => ['method' => 'handleProductChange', 'priority' => 10],
'sirsoft-ecommerce.product.after_delete' => ['method' => 'handleProductChange', 'priority' => 10],
];
}
/**
* 상품 변경 시 캐시 무효화
*
* @param mixed ...$args
* @return void
*/
public function handleProductChange(...$args): void
{
// 모든 상품 목록 캐시 삭제
Cache::forget('products.all');
Cache::forget('products.active');
// 특정 상품 캐시 삭제
if (isset($args[0]->id)) {
Cache::forget("product.{$args[0]->id}");
}
Log::info('상품 캐시가 무효화되었습니다.', [
'product_id' => $args[0]->id ?? null,
]);
}
}
```
---
## 코어 리스너 자동 발견
코어 애플리케이션의 훅 리스너는 `app/Listeners/` 디렉토리에서 **자동 발견**됩니다. `HookListenerInterface`를 구현한 클래스는 별도 등록 없이 자동으로 HookManager에 등록됩니다.
### 자동 발견 조건
| 조건 | 설명 |
|------|------|
| 위치 | `app/Listeners/` 및 모든 하위 디렉토리 |
| 인터페이스 | `HookListenerInterface` 구현 필수 |
| 등록 방식 | `CoreServiceProvider::boot()`에서 재귀 스캔 |
### 디렉토리 구조 예시
```text
app/Listeners/
├── ActivityLogListener.php ✅ 자동 발견
├── CoreActivityLogListener.php ✅ 자동 발견
├── ExtensionCompatibilityAlertListener.php ✅ 자동 발견
├── Dashboard/
│ ├── DashboardModuleListener.php ✅ 자동 발견 (하위 디렉토리)
│ └── DashboardStatsListener.php ✅ 자동 발견 (하위 디렉토리)
└── UserLogin/
└── UpdateLastLoginListener.php ✅ 자동 발견 (하위 디렉토리)
```
### CoreServiceProvider 구현
```php
// app/Providers/CoreServiceProvider.php
private function registerCoreHookListeners(): void
{
$listenersPath = app_path('Listeners');
if (! is_dir($listenersPath)) {
return;
}
// 재귀적으로 모든 PHP 파일 스캔
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($listenersPath, \RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->getExtension() !== 'php') {
continue;
}
// 파일 경로에서 클래스명 추출
$relativePath = str_replace($listenersPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
$relativePath = str_replace('.php', '', $relativePath);
$relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
$listenerClass = 'App\\Listeners\\'.$relativePath;
// 클래스 존재 여부 확인
if (! class_exists($listenerClass)) {
Log::warning("코어 훅 리스너 클래스를 찾을 수 없습니다: {$listenerClass}");
continue;
}
// HookListenerInterface 구현 여부 확인
if (! in_array(HookListenerInterface::class, class_implements($listenerClass))) {
continue;
}
$this->registerCoreHookListener($listenerClass);
}
}
```
### 장점
| 장점 | 설명 |
|------|------|
| 자동 활성화 | 리스너 파일 생성만으로 훅 구독 시작 |
| ServiceProvider 수정 불필요 | 새 리스너 추가 시 코드 변경 없음 |
| 모듈/플러그인과 동일 패턴 | 일관된 아키텍처 |
| 메모리 효율 | 클로저 래퍼로 지연 인스턴스 생성 |
### 모듈/플러그인과의 차이점
| 항목 | 코어 리스너 | 모듈/플러그인 리스너 |
|------|------------|-------------------|
| 발견 방식 | 디렉토리 재귀 스캔 | `getHookListeners()` 메서드 |
| 위치 | `app/Listeners/**/*.php` | `modules/**/Listeners/`, `plugins/**/Listeners/` |
| 등록 주체 | `CoreServiceProvider` | `ModuleServiceProvider`, `PluginServiceProvider` |
---
## 우선순위 가이드라인
**우선순위 범위**: 1 ~ 100 (낮을수록 먼저 실행)
| 우선순위 | 용도 | 예시 |
| -------- | ---------- | ------------------ |
| 1-5 | 매우 높음 | 데이터 검증, 보안 체크 |
| 10 | 기본값 | 일반 리스너 |
| 15-20 | 낮음 | 알림, 로깅 |
| 25+ | 매우 낮음 | 분석, 통계 |
### 정렬 메커니즘
HookManager는 `ksort()`를 사용하여 우선순위별 정렬 후 실행합니다:
| 규칙 | 설명 |
| ---- | ---- |
| 정렬 방식 | `ksort()` — 숫자 오름차순 (낮을수록 먼저 실행) |
| 기본값 | `$priority = 10` (`addAction`, `addFilter` 공통) |
| 동일 우선순위 | 등록 순서대로 실행 (FIFO — 배열 push 순서 유지) |
```php
// 우선순위 5 → 10 → 20 순서로 실행
HookManager::addAction('order.created', $securityCheck, 5);
HookManager::addAction('order.created', $businessLogic, 10);
HookManager::addAction('order.created', $notification, 20);
```
---
## 모듈에 리스너 등록
### module.php에서 등록
```php
<?php
namespace Modules\Sirsoft\Ecommerce;
use App\Contracts\Extension\ModuleInterface;
use Modules\Sirsoft\Ecommerce\Listeners\ProductCacheInvalidationListener;
use Modules\Sirsoft\Ecommerce\Listeners\OrderNotificationListener;
class Module implements ModuleInterface
{
// ... 기타 메서드들 ...
/**
* 훅 리스너 목록 반환
*
* @return array
*/
public function getHookListeners(): array
{
return [
ProductCacheInvalidationListener::class,
OrderNotificationListener::class,
];
}
}
```
---
## Service에서 훅 사용 패턴
```php
<?php
namespace Modules\Sirsoft\Ecommerce\Services;
use App\Extension\HookManager;
use Modules\Sirsoft\Ecommerce\Repositories\ProductRepository;
class ProductService
{
public function __construct(
private ProductRepository $productRepository
) {}
public function createProduct(array $data): Product
{
// 1. Before 훅 - 데이터 검증, 전처리
HookManager::doAction('sirsoft-ecommerce.product.before_create', $data);
// 2. 필터 훅 - 데이터 변형
$data = HookManager::applyFilters('sirsoft-ecommerce.product.filter_create_data', $data);
// 3. 비즈니스 로직 실행
$product = $this->productRepository->create($data);
// 4. After 훅 - 후처리, 알림, 캐시 등
HookManager::doAction('sirsoft-ecommerce.product.after_create', $product, $data);
return $product;
}
public function calculateProductPrice(Product $product): float
{
$basePrice = $product->price;
// 필터 훅으로 가격 계산 (할인, 세금 등)
$finalPrice = HookManager::applyFilters(
'sirsoft-ecommerce.product.calculate_price',
$basePrice,
$product
);
return $finalPrice;
}
}
```
---
## 필터 훅 리스너 예시
### `type` 필드 사용법
`getSubscribedHooks()` 메서드에서 `type` 필드를 사용하여 훅 타입을 명시해야 합니다.
| type 값 | 설명 | 기본값 |
|---------|------|--------|
| `action` | Action 훅 - 반환값 없음 | ✅ (생략 시 기본값) |
| `filter` | Filter 훅 - 반환값 필수 | |
**중요**: Filter 훅 리스너는 반드시 `'type' => 'filter'`를 명시해야 합니다. 명시하지 않으면 Action 훅으로 처리되어 **반환값이 무시**됩니다.
### Filter 훅 리스너 구현
```php
<?php
namespace Modules\Sirsoft\Ecommerce\Listeners;
use App\Contracts\Extension\HookListenerInterface;
class ProductPriceCalculationListener implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
// Filter 훅은 반드시 'type' => 'filter' 명시
'sirsoft-ecommerce.product.calculate_price' => [
'method' => 'applyDiscounts',
'priority' => 10,
'type' => 'filter', // 필수!
],
];
}
/**
* 할인 적용
*
* @param float $price 기본 가격
* @param Product $product 상품 객체
* @return float 할인 적용된 가격
*/
public function applyDiscounts(float $price, $product): float
{
// 10% 할인 적용 (예시)
if ($product->category->name === 'Special') {
$price = $price * 0.9;
}
return $price; // 반드시 값을 반환해야 함
}
}
```
### Action과 Filter 혼합 사용
하나의 리스너에서 Action 훅과 Filter 훅을 함께 구독할 수 있습니다:
```php
<?php
namespace Modules\Sirsoft\Board\Listeners;
use App\Contracts\Extension\HookListenerInterface;
use App\Models\User;
class UserNotificationSettingsListener implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
// Filter 훅: 데이터 변형 (type 필수)
'core.user.filter_create_data' => [
'method' => 'filterCreateData',
'priority' => 10,
'type' => 'filter',
],
'core.user.filter_update_data' => [
'method' => 'filterUpdateData',
'priority' => 10,
'type' => 'filter',
],
'core.user.filter_resource_data' => [
'method' => 'filterResourceData',
'priority' => 10,
'type' => 'filter',
],
// Action 훅: 부가 작업 (type 생략 가능)
'core.user.after_create' => [
'method' => 'afterCreate',
'priority' => 10,
// type 생략 = 'action'
],
];
}
/**
* 생성 데이터 필터: 모듈 필드 추출 후 제거
*
* @param array $data 요청 데이터
* @return array 모듈 필드가 제거된 데이터
*/
public function filterCreateData(array $data): array
{
// 모듈 필드 추출 및 임시 저장
$moduleData = $this->extractModuleData($data);
session(['module_data' => $moduleData]);
// 모듈 필드 제거 후 반환
return $this->removeModuleFields($data);
}
/**
* 생성 후 액션: 임시 저장된 데이터로 모듈 데이터 저장
*
* @param User $user 생성된 사용자
* @param array $originalData 원본 요청 데이터
* @return void
*/
public function afterCreate(User $user, array $originalData): void
{
$moduleData = session('module_data', []);
session()->forget('module_data');
if (!empty($moduleData)) {
$this->saveModuleData($user->id, $moduleData);
}
}
/**
* API 응답 필터: 모듈 데이터 병합
*
* @param array $data API 응답 데이터
* @param User $user 조회 대상 사용자
* @return array 모듈 데이터가 병합된 응답
*/
public function filterResourceData(array $data, User $user): array
{
$moduleData = $this->getModuleData($user->id);
return array_merge($data, $moduleData);
}
}
```
### SEO 훅 활용 예시 — 리뷰 플러그인이 JSON-LD에 리뷰 데이터 주입
```php
<?php
namespace Plugins\Sirsoft\Reviews\Listeners;
use App\Extension\Contracts\HookListenerInterface;
class SeoReviewMetaListener implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
'core.seo.filter_meta' => [
'method' => 'injectReviewJsonLd',
'priority' => 10,
'type' => 'filter', // 필수!
],
];
}
/**
* SEO 메타에 리뷰 JSON-LD를 주입합니다.
*
* @param array $meta 메타 태그 배열
* @param array $hookMeta 훅 메타 정보 (layoutName, moduleIdentifier 등)
* @return array 수정된 메타 배열
*/
public function injectReviewJsonLd(array $meta, array $hookMeta): array
{
// 상품 상세 페이지에서만 동작
if ($hookMeta['moduleIdentifier'] !== 'sirsoft-ecommerce') {
return $meta;
}
$context = $hookMeta['context'] ?? [];
$productId = $context['route']['id'] ?? null;
if (! $productId) {
return $meta;
}
// 리뷰 데이터 조회 및 JSON-LD 주입
$reviews = $this->getReviewAggregate($productId);
if ($reviews && $meta['jsonLd']) {
$jsonLd = json_decode($meta['jsonLd'], true);
$jsonLd['aggregateRating'] = [
'@type' => 'AggregateRating',
'ratingValue' => $reviews['average'],
'reviewCount' => $reviews['count'],
];
$meta['jsonLd'] = json_encode($jsonLd, JSON_UNESCAPED_UNICODE);
}
return $meta;
}
}
```
### 훅 타입별 동작 비교
| 구분 | Action 훅 | Filter 훅 |
|------|----------|-----------|
| `type` 필드 | 생략 가능 (`'action'` 기본값) | **필수** (`'type' => 'filter'`) |
| 반환값 | 무시됨 | **필수** (다음 필터로 전달) |
| HookManager 메서드 | `doAction()` | `applyFilters()` |
| 사용 목적 | 부가 작업 (로그, 알림, 캐시 등) | 데이터 변형 (필터링, 병합, 제거 등) |
---
## 훅 내부 메커니즘
### 중복 실행 방지 (가드 플래그)
HookManager는 `$dispatching` 배열을 사용하여 동일 훅의 중복 실행을 방지합니다. Laravel Event 시스템과의 하이브리드 동작에서 발생할 수 있는 무한 루프를 차단합니다.
```text
doAction('hook.name')
→ $dispatching['hook.name'] = true (가드 설정)
→ Event::dispatch('hook.name')
→ 리스너 실행 중 doAction('hook.name') 재호출 시
→ $dispatching 체크 → 스킵 (중복 방지)
→ unset($dispatching['hook.name']) (가드 해제)
```
### addAction/addFilter 내부 동작
```text
addAction() → Event::listen() 등록 + 리스너 배열 관리
addFilter() → Event::listen() 등록 + 리스너 배열 관리 (동일)
removeAction() / removeFilter() → Event::forget() + 배열에서 제거
```
---
## 훅 권한 시스템
G7은 훅 실행 시 **권한 체크**를 지원합니다. `permission_hooks` 테이블을 통해 특정 훅을 실행하려면 어떤 권한이 필요한지 매핑할 수 있습니다.
### 하이브리드 권한 체계
```text
┌─────────────────────────────────────────────────────────────┐
│ 권한 체크 레이어 │
├─────────────────────────────────────────────────────────────┤
│ 1단계: permission_hooks (기능 레벨) │
│ → 'core.attachment.download' 훅 실행 권한 │
│ → 이 기능 자체를 사용할 수 있는가? │
│ → 미매핑 시 모든 사용자 허용 │
│ → 매핑 시 해당 퍼미션 보유자만 허용 │
├─────────────────────────────────────────────────────────────┤
│ 2단계: role_* (리소스 레벨) │
│ → 특정 파일/메뉴에 대한 접근 권한 │
│ → 이 리소스를 읽을/수정할/삭제할 수 있는가? │
│ → 현행 로직 유지 │
└─────────────────────────────────────────────────────────────┘
```
### permission_hooks 테이블
```php
Schema::create('permission_hooks', function (Blueprint $table) {
$table->id();
$table->foreignId('permission_id')->constrained()->cascadeOnDelete();
$table->string('hook_name')->comment('훅 이름 (예: core.attachment.download)');
$table->timestamps();
$table->unique(['permission_id', 'hook_name']);
$table->index('hook_name');
});
```
### PermissionHook 모델
```php
// app/Models/PermissionHook.php
class PermissionHook extends Model
{
protected $fillable = ['permission_id', 'hook_name'];
public function permission(): BelongsTo
{
return $this->belongsTo(Permission::class);
}
/**
* 특정 훅에 매핑된 권한 ID 목록 조회
*/
public static function getPermissionsForHook(string $hookName): array
{
return static::where('hook_name', $hookName)
->pluck('permission_id')
->toArray();
}
/**
* 훅에 권한이 매핑되어 있는지 확인
*/
public static function hasPermissionMapping(string $hookName): bool
{
return static::where('hook_name', $hookName)->exists();
}
}
```
### HookManager의 권한 체크 메서드
```php
// app/Extension/HookManager.php
class HookManager
{
/**
* 훅 실행 전 권한 체크
*
* @param string $hookName 훅 이름
* @param User|null $user 사용자 (null이면 비로그인)
* @return bool 실행 허용 여부
*/
public static function checkHookPermission(string $hookName, ?User $user): bool
{
// 1. 훅에 매핑된 권한이 없으면 모든 사용자 허용
if (!PermissionHook::hasPermissionMapping($hookName)) {
return true;
}
// 2. 비로그인 사용자는 권한 매핑된 훅 실행 불가
if ($user === null) {
return false;
}
// 3. 관리자는 모든 훅 실행 가능
if ($user->hasRole('admin')) {
return true;
}
// 4. 사용자의 역할에 해당 권한이 있는지 확인
$requiredPermissionIds = PermissionHook::getPermissionsForHook($hookName);
return $user->roles()
->whereHas('permissions', function ($query) use ($requiredPermissionIds) {
$query->whereIn('permissions.id', $requiredPermissionIds);
})
->exists();
}
/**
* 권한 체크 후 Action 실행
*
* @param string $hookName 훅 이름
* @param User|null $user 사용자
* @param mixed ...$args 훅 인자
* @return bool 실행 성공 여부
*/
public static function doActionWithPermission(string $hookName, ?User $user, ...$args): bool
{
if (!static::checkHookPermission($hookName, $user)) {
return false;
}
static::doAction($hookName, ...$args);
return true;
}
/**
* 권한 체크 후 Filter 적용
*
* @param string $hookName 훅 이름
* @param User|null $user 사용자
* @param mixed $value 필터링할 값
* @param mixed ...$args 추가 인자
* @return mixed 필터링된 값 (권한 없으면 원본 반환)
*/
public static function applyFiltersWithPermission(string $hookName, ?User $user, $value, ...$args)
{
if (!static::checkHookPermission($hookName, $user)) {
return $value;
}
return static::applyFilters($hookName, $value, ...$args);
}
}
```
### 훅에 권한 매핑하기
```php
// 시더 또는 관리자 기능에서
// 'attachment.download' 권한을 'core.attachment.download' 훅에 매핑
$permission = Permission::where('identifier', 'attachment.download')->first();
PermissionHook::create([
'permission_id' => $permission->id,
'hook_name' => 'core.attachment.download',
]);
```
### 권한 매핑 해제 (모든 사용자 허용)
```php
PermissionHook::where('hook_name', 'core.attachment.download')->delete();
```
### Service에서 사용 예시
```php
// app/Services/AttachmentService.php
public function download(int $id, ?User $user): ?Attachment
{
// 1단계: 기능 레벨 권한 체크 (permission_hooks)
if (!HookManager::checkHookPermission('core.attachment.download', $user)) {
throw new AuthorizationException(__('attachment.download_permission_denied'));
}
$attachment = $this->repository->findById($id);
// 2단계: 리소스 레벨 권한 체크 (role_attachments)
if (!$this->checkResourcePermission($user, $attachment, AttachmentPermissionType::Read)) {
throw new AuthorizationException(__('attachment.resource_access_denied'));
}
return $attachment;
}
```
### 권한 체크 흐름 요약
```text
┌─────────────────────────────────────────────────────────────┐
│ checkHookPermission() 흐름 │
├─────────────────────────────────────────────────────────────┤
│ 1. permission_hooks에 훅 매핑 확인 │
│ → 매핑 없음: 모든 사용자 허용 (return true) │
├─────────────────────────────────────────────────────────────┤
│ 2. 비로그인 사용자 │
│ → 매핑 있으면 거부 (return false) │
├─────────────────────────────────────────────────────────────┤
│ 3. 관리자(admin) 역할 │
│ → 모든 훅 실행 허용 (return true) │
├─────────────────────────────────────────────────────────────┤
│ 4. 사용자 역할의 권한 확인 │
│ → 매핑된 권한 보유 여부 반환 │
└─────────────────────────────────────────────────────────────┘
```
---
### SEO 캐시 무효화 리스너
모듈의 CRUD 훅에서 SEO 캐시를 무효화하는 패턴:
| 훅 | 리스너 메서드 | 무효화 대상 |
|----|-------------|-----------|
| `[module].product.after_create` | `onProductChange` | 해당 URL + 목록/카테고리 |
| `[module].product.after_update` | `onProductUpdate` | 해당 URL + 목록 |
| `[module].*.after_delete` | `onProductChange` | 전체 관련 캐시 |
캐시 무효화 시 `Cache::forget('seo:sitemap')`도 함께 호출
> 구현 상세: [seo-system.md](../backend/seo-system.md)
---
## 관련 문서
- [모듈 개발 기초](module-basics.md) - 모듈에서 훅 리스너 등록
- [Service-Repository 패턴](../backend/service-repository.md) - Service에서 훅 실행 패턴
- [활동 로그 시스템](../backend/activity-log.md) - 활동 로그 Listener 작성 패턴, Per-Item Bulk 로깅 규칙
- [권한 시스템](permissions.md) - Permission, Role 체계
- [확장 시스템 인덱스](index.md) - 전체 확장 시스템 개요
+682
View File
@@ -0,0 +1,682 @@
# 레이아웃 확장 시스템 (Layout Extensions)
> 모듈/플러그인이 기존 레이아웃에 동적으로 UI를 주입하는 시스템입니다.
## 목차
- [개요](#개요)
- [핵심 원칙](#핵심-원칙)
- [확장 타입](#확장-타입)
- [Extension 파일 위치](#extension-파일-위치)
- [Overlay 확장](#overlay-확장)
- [Extension Point 확장](#extension-point-확장)
- [템플릿 오버라이드](#템플릿-오버라이드)
- [모듈 활성화/비활성화 동작](#모듈-활성화비활성화-동작)
- [우선순위](#우선순위)
- [데이터 소스 병합](#데이터-소스-병합)
- [모달 병합](#모달-병합)
- [Overlay 레이아웃 섹션 병합](#overlay-레이아웃-섹션-병합)
- [관련 파일](#관련-파일)
- [문제 해결](#문제-해결)
---
## 개요
Layout Extension 시스템은 모듈/플러그인이 코어 또는 다른 확장의 레이아웃에 UI 컴포넌트를 동적으로 주입할 수 있게 해줍니다.
**주요 특징**:
- 코어 레이아웃 수정 없이 UI 확장
- 모듈 비활성화 시 자동으로 확장 UI 숨김
- 템플릿에서 모듈 확장 오버라이드 가능
- 우선순위 기반 렌더링 순서 제어
---
## 핵심 원칙
```text
필수: layout_extensions 통한 동적 주입 사용 (코어 레이아웃에 모듈 UI 하드코딩 금지)
필수: Layout Extension 시스템을 통한 동적 UI 주입
필수: 모듈 비활성화 시 관련 UI 자동 숨김
✅ 필수: 확장 컴포넌트에 ExtensionBadge 표시 (관리자 UI)
필수: 플러그인은 완전한 레이아웃 등록 불가 → 확장 지점(layout_extensions)만 사용
(예외: settings.json 환경설정 레이아웃은 registerPluginLayouts()로 등록)
필수: 모듈만 완전한 레이아웃 등록 가능 (admin/user 모두)
```
---
## 확장 타입
| 타입 | 키 | 설명 | 사용 시점 |
|------|-----|------|----------|
| **Overlay** | `target_layout` | 기존 레이아웃의 특정 컴포넌트 ID를 찾아 주입 | 특정 위치에 삽입/추가 |
| **Extension Point** | `extension_point` | 레이아웃에 사전 정의된 확장 포인트에 주입 | 확장용 영역이 미리 정의된 경우 |
---
## Extension 파일 위치
### 모듈
```
modules/
└── vendor-module/
└── resources/
└── extensions/ ← 확장 정의 디렉토리
└── *.json ← 확장 JSON 파일
```
### 플러그인
```
plugins/
└── vendor-plugin/
└── resources/
└── extensions/
└── *.json
```
### 템플릿 오버라이드
```
templates/
└── vendor-template/
└── extensions/
└── {module-identifier}/ ← 오버라이드 대상 모듈
└── *.json ← 오버라이드 JSON
```
---
## Overlay 확장
기존 레이아웃의 특정 컴포넌트를 찾아 UI를 주입합니다.
### JSON 스키마
```json
{
"target_layout": "admin_user_form",
"injections": [
{
"target_id": "section_marketing_consent",
"position": "append",
"components": [...]
}
],
"data_sources": [...],
"priority": 100
}
```
### 필드 설명
| 필드 | 필수 | 타입 | 설명 |
|------|------|------|------|
| `target_layout` | ✅ | string | 확장할 대상 레이아웃 이름 |
| `injections` | ✅ | array | 주입 정의 배열 |
| `injections[].target_id` | ✅ | string | 주입 대상 컴포넌트 ID |
| `injections[].position` | ✅ | string | 주입 위치 (아래 참조) |
| `injections[].components` | ✅ | array | 주입할 컴포넌트 배열 |
| `data_sources` | ❌ | array | 추가 데이터 소스 (선택) |
| `priority` | ❌ | number | 우선순위 (기본값: 100, 낮을수록 먼저) |
### position 옵션
| 값 | 설명 | 다이어그램 |
|-----|------|----------|
| `prepend` | 타겟 **앞에** 형제로 삽입 | `[NEW] [TARGET] [siblings...]` |
| `append` | 타겟 **뒤에** 형제로 삽입 | `[TARGET] [NEW] [siblings...]` |
| `prepend_child` | 타겟 children **맨 앞에** 삽입 | `TARGET { [NEW] [children...] }` |
| `append_child` | 타겟 children **맨 뒤에** 삽입 | `TARGET { [children...] [NEW] }` |
| `replace` | 타겟 **완전 교체** | `[NEW]` (기존 타겟 제거) |
| `inject_props` | 타겟 컴포넌트의 **props에 값 주입** | `TARGET.props ← injection.props` |
### inject_props 상세
`inject_props`는 기존 컴포넌트의 props에 값을 주입하는 특수 position입니다. `components` 필드 대신 `props` 필드를 사용합니다.
#### 병합 전략
| 전략 | 설명 | 예시 |
|------|------|------|
| `_append` | 배열 끝에 추가 | `tabs._append: [newTab]` → 기존 tabs 뒤에 추가 |
| `_prepend` | 배열 앞에 추가 | `tabs._prepend: [newTab]` → 기존 tabs 앞에 추가 |
| `_merge` | 객체 병합 (shallow) | `style._merge: {color: 'red'}` → 기존 style에 병합 |
| (직접 값) | 스칼라 덮어쓰기 | `disabled: true` → 기존 값 대체 |
#### inject_props 예시: 탭에 항목 추가
```json
{
"target_layout": "admin_user_detail",
"injections": [
{
"target_id": "user_detail_tabs",
"position": "inject_props",
"props": {
"tabs": {
"_append": [
{
"id": "ext_verification",
"label": "$t:admin.users.form.sections.verification_info",
"iconName": "shield"
}
]
}
}
},
{
"target_id": "extension_tab_content",
"position": "append_child",
"components": [
{
"id": "ext_verification_content",
"type": "basic",
"name": "Div",
"if": "{{(_global.activeUserDetailTab || query.tab || 'basic') === 'ext_verification'}}",
"children": [...]
}
]
}
],
"priority": 100
}
```
#### 주의사항
- `inject_props`일 때 `components` 필드는 무시됩니다
- 대상 prop이 표현식 문자열인 경우 `_append`/`_prepend`/`_merge` 적용이 불가하며, 경고 로그가 기록됩니다
- `_append`와 `_merge` 등 여러 전략을 하나의 prop에 혼합 사용할 수 없습니다 (첫 번째 매칭 전략 우선)
### 예시: 사용자 폼에 알림 설정 추가
```json
{
"target_layout": "admin_user_form",
"injections": [
{
"target_id": "section_marketing_consent",
"position": "append",
"components": [
{
"id": "section_notification_settings",
"type": "basic",
"name": "Div",
"props": {
"className": "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6 mb-6"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": {
"className": "flex items-center justify-between mb-4"
},
"children": [
{
"type": "basic",
"name": "H3",
"props": {
"className": "text-lg font-semibold text-gray-900 dark:text-white"
},
"text": "$t:sirsoft-board.admin.users.form.sections.notification_settings"
},
{
"type": "composite",
"name": "ExtensionBadge",
"props": {
"type": "module",
"identifier": "sirsoft-board",
"installedModules": "{{_global.installedModules}}"
}
}
]
},
{
"type": "basic",
"name": "Input",
"props": {
"type": "checkbox",
"name": "notify_post_complete",
"checked": "{{_local.form?.notify_post_complete ?? false}}"
}
}
]
}
]
}
],
"priority": 100
}
```
---
## Extension Point 확장
레이아웃에 미리 정의된 확장 포인트에 컴포넌트를 주입합니다.
### 지원 위치
Extension Point는 레이아웃의 다음 섹션에서 사용할 수 있습니다:
| 위치 | 지원 | 설명 |
|----------------|------|--------------------------------------|
| `components` | ✅ | 메인 컴포넌트 트리 (기본) |
| `modals` | ✅ | 모달 내부 컴포넌트 트리 (v1.17.0+) |
```text
v1.17.0 이전: modals 내부의 extension_point는 처리되지 않았음
✅ v1.17.0+: components와 modals 양쪽 모두 재귀적으로 extension_point 처리
```
### 레이아웃에서 Extension Point 정의
```json
{
"layout_name": "admin_user_form",
"components": [
{
"id": "user_form_container",
"type": "basic",
"name": "Div",
"children": [
{
"type": "extension_point",
"name": "user_form_additional_fields",
"default": []
}
]
}
]
}
```
### 모듈에서 Extension Point에 주입
```json
{
"extension_point": "user_form_additional_fields",
"mode": "replace",
"components": [
{
"id": "custom_field_section",
"type": "basic",
"name": "Div",
"children": [...]
}
],
"data_sources": [...],
"priority": 100
}
```
### JSON 스키마
| 필드 | 필수 | 타입 | 설명 |
|------|------|------|------|
| `extension_point` | ✅ | string | 확장 포인트 이름 |
| `mode` | ❌ | string | 주입 모드 (아래 참조, 기본값: `append`) |
| `components` | ❌ | array | 주입할 컴포넌트 배열 |
| `data_sources` | ❌ | array | 추가 데이터 소스 |
| `modals` | ❌ | array | 호스트 레이아웃에 병합할 모달 배열 |
| `scripts` | ❌ | array | 추가 스크립트 |
| `priority` | ❌ | number | 우선순위 (기본값: 100) |
### mode 옵션
| 값 | 설명 | 동작 |
| ----- | ------ | ------ |
| `append` | default **뒤에** 추가 (기본값) | `[default...] [NEW]` |
| `prepend` | default **앞에** 추가 | `[NEW] [default...]` |
| `replace` | default **완전 교체** | `[NEW]` (default 제거) |
---
## 템플릿 오버라이드
템플릿은 모듈/플러그인의 확장을 오버라이드하여 커스터마이징할 수 있습니다.
### 디렉토리 구조
```
templates/_bundled/sirsoft-admin_basic/
└── extensions/
└── sirsoft-board/ ← 오버라이드 대상 모듈
└── user-notification-settings.json ← 오버라이드 파일
```
### 오버라이드 파일명 규칙
모듈의 원본 확장 파일명과 **동일한 이름**을 사용합니다.
```
모듈 원본: modules/_bundled/sirsoft-board/resources/extensions/user-notification-settings.json
템플릿 오버라이드: templates/_bundled/sirsoft-admin_basic/extensions/sirsoft-board/user-notification-settings.json
```
### 오버라이드 우선순위
```
1. 템플릿 오버라이드 (source_type = Template) ← 가장 높은 우선순위
2. 플러그인 확장 (source_type = Plugin)
3. 모듈 확장 (source_type = Module) ← 가장 낮은 우선순위
```
### 오버라이드 예시
모듈의 기본 확장을 템플릿에서 스타일 변경:
```json
{
"target_layout": "admin_user_form",
"injections": [
{
"target_id": "section_marketing_consent",
"position": "append",
"components": [
{
"id": "section_notification_settings",
"type": "basic",
"name": "Div",
"props": {
"className": "bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 rounded-lg p-6 mb-6"
},
"children": [...]
}
]
}
],
"priority": 100
}
```
---
## 모듈 활성화/비활성화 동작
### 활성화 시
1. `resources/extensions/*.json` 파일 스캔
2. `template_layout_extensions` 테이블에 등록 (또는 기존 레코드 복원)
3. 레이아웃 캐시 무효화
### 비활성화 시
1. 해당 모듈의 확장 레코드 Soft Delete
2. **렌더링 시 비활성화된 모듈의 확장 자동 스킵**
3. 레이아웃 캐시 무효화
### 템플릿 오버라이드와 모듈 비활성화
**중요**: 모듈이 비활성화되면, 해당 모듈을 오버라이드하는 템플릿 확장도 함께 숨김 처리됩니다.
```
sirsoft-board 모듈 비활성화
↓
sirsoft-board의 모든 확장 숨김
↓
sirsoft-board를 오버라이드하는 템플릿 확장도 숨김
```
---
## 우선순위
### priority 필드
- 기본값: 100
- 낮을수록 먼저 렌더링
- 같은 위치에 여러 확장이 있을 경우 순서 결정
```json
{
"target_layout": "admin_user_form",
"priority": 50,
"injections": [...]
}
```
### 우선순위 가이드라인
| 범위 | 용도 | 예시 |
|------|------|------|
| 1-25 | 필수 정보 | 보안 경고, 중요 알림 |
| 50-75 | 주요 기능 | 핵심 모듈 UI |
| 100 | 기본값 | 일반 확장 |
| 150+ | 보조 정보 | 분석, 통계 |
---
## 데이터 소스 병합
확장에서 정의한 `data_sources`는 호스트 레이아웃의 데이터 소스에 병합됩니다.
```json
{
"target_layout": "admin_user_form",
"injections": [...],
"data_sources": [
{
"id": "notification_settings",
"type": "api",
"method": "GET",
"endpoint": "/api/modules/sirsoft-board/admin/users/{{route.id}}/notification-settings",
"auto_fetch": true,
"auth_required": true
}
]
}
```
---
## 모달 병합
Extension Point 확장에서 정의한 `modals`는 호스트 레이아웃의 `modals` 배열에 자동 병합됩니다.
### 왜 modals 섹션을 사용해야 하는가?
Extension Point의 children으로 주입된 인라인 Modal(`show` prop 기반)은 정상 동작하지 않습니다. 그누보드7 Modal 시스템에서 안정적으로 동작하려면 `modals` 섹션에 등록하고 `openModal`/`closeModal` 핸들러로 제어해야 합니다.
> 상세 모달 규칙: [modal-usage.md](../frontend/modal-usage.md)
### Extension JSON에서 modals 정의
```json
{
"extension_point": "shop_checkout_extensions",
"modals": [
{
"id": "payment_error_modal",
"type": "composite",
"name": "Modal",
"props": {
"title": "$t:plugin.payment_error_title",
"size": "small"
},
"children": [...]
}
],
"priority": 100
}
```
### 핸들러에서 모달 열기
Extension으로 병합된 모달은 커스텀 핸들러에서 `G7Core.modal.open()`으로 열 수 있습니다:
```typescript
const G7Core = (window as any).G7Core;
G7Core?.modal?.open?.('payment_error_modal');
```
또는 레이아웃 JSON 액션에서:
```json
{
"type": "click",
"handler": "openModal",
"target": "payment_error_modal"
}
```
### 병합 동작
- 여러 확장의 `modals`가 하나의 호스트 레이아웃에 모두 병합됩니다
- 호스트 레이아웃에 기존 `modals`가 있으면 확장 모달이 뒤에 추가됩니다
- 확장에 `modals`가 없으면 호스트 레이아웃에 영향 없음 (하위 호환)
### 주의사항
```text
modals 섹션 모달에 show prop 사용 금지 (무시됨)
모달 ID는 호스트 레이아웃의 기존 모달과 중복되지 않도록 플러그인 prefix 사용 권장
✅ 모달 닫기 시 setState → closeModal 순서 유지 (순서 중요)
```
---
## Overlay 레이아웃 섹션 병합
Overlay 확장에서 `computed`, `state`, `modals` 섹션을 정의하면 호스트 레이아웃에 자동 병합됩니다.
### 지원 섹션
| 섹션 | Extension Point | Overlay | 설명 |
|------|:---:|:---:|------|
| `data_sources` | ✅ | ✅ | API 데이터 소스 추가 |
| `scripts` | ✅ | ✅ | 커스텀 핸들러 스크립트 추가 |
| `modals` | ✅ | ✅ | 모달 컴포넌트 추가 |
| `computed` | ✅ | ✅ | 계산된 값 추가 |
| `state` | ✅ | ✅ | 초기 상태 추가 |
### 예시: Overlay에서 computed와 state 추가
```json
{
"target_layout": "admin_user_detail",
"injections": [...],
"computed": {
"verificationStatus": "{{user?.data?.identity_verified ? 'verified' : 'pending'}}"
},
"state": {
"showVerificationHistory": false
},
"modals": [
{
"id": "ext_verification_modal",
"type": "composite",
"name": "Modal",
"props": { "title": "인증 이력" },
"children": [...]
}
],
"priority": 100
}
```
### 병합 동작
- 여러 overlay의 같은 섹션은 priority 오름차순으로 순차 병합됩니다
- 동일 키 충돌 시 후순위 overlay가 덮어씁니다
- 해당 섹션이 없는 overlay는 기존 레이아웃에 영향 없음 (하위 호환)
---
## 레이아웃 오버라이드 vs 확장 오버라이드
| 구분 | 레이아웃 오버라이드 | 확장 오버라이드 |
|------|-------------------|---------------|
| 대상 | 모듈이 등록한 완전한 레이아웃 | 확장 지점/Overlay로 주입된 UI |
| 위치 | `templates/{t}/layouts/overrides/{module}/*.json` | `templates/{t}/extensions/{module}/*.json` |
| DB 테이블 | `template_layouts` | `template_layout_extensions` |
| 해석 서비스 | `LayoutResolverService` | `LayoutExtensionService` |
| version_constraint | 지원 | 지원 |
---
## 관련 파일
### 백엔드
| 파일 | 설명 |
|------|------|
| `app/Services/LayoutExtensionService.php` | 확장 적용 핵심 서비스 |
| `app/Models/LayoutExtension.php` | 확장 모델 (DB 테이블) |
| `app/Repositories/LayoutExtensionRepository.php` | 확장 Repository |
| `app/Enums/LayoutExtensionType.php` | 확장 타입 Enum (ExtensionPoint, Overlay) |
| `app/Enums/LayoutSourceType.php` | 출처 타입 Enum (Module, Plugin, Template) |
### 데이터베이스
| 테이블 | 설명 |
|--------|------|
| `template_layout_extensions` | 확장 등록 정보 저장 |
### 주요 컬럼
```
template_layout_extensions
├── template_id # 템플릿 ID
├── extension_type # ExtensionPoint | Overlay
├── target_name # 확장 포인트명 또는 대상 레이아웃명
├── source_type # Module | Plugin | Template
├── source_identifier # 모듈/플러그인/템플릿 식별자
├── override_target # 오버라이드 대상 (템플릿 오버라이드 시)
├── content # 확장 JSON 내용
├── priority # 우선순위
├── is_active # 활성 상태
└── deleted_at # Soft Delete
```
---
## 문제 해결
### 확장이 표시되지 않음
**확인 사항**:
1. 모듈/플러그인이 활성화되어 있는지 확인
2. `target_layout` 또는 `extension_point` 이름이 정확한지 확인
3. `target_id`가 대상 레이아웃에 존재하는지 확인
4. JSON 문법 오류 확인
**캐시 초기화**:
```bash
php artisan cache:clear
```
### 오버라이드가 적용되지 않음
**확인 사항**:
1. 템플릿 오버라이드 파일 경로 확인
- `templates/{template}/extensions/{module-identifier}/{filename}.json`
2. 파일명이 원본과 동일한지 확인
3. `template_layout_extensions` 테이블에서 `source_type = 'template'` 레코드 확인
### 모듈 비활성화 후에도 확장 표시됨
**원인**: 캐시 문제
**해결**:
```bash
php artisan cache:clear
```
### 여러 확장의 순서가 예상과 다름
**해결**: `priority` 값 조정 (낮을수록 먼저 렌더링)
---
## 관련 문서
- [module-layouts.md](module-layouts.md) - 모듈 레이아웃 등록
- [hooks.md](hooks.md) - 훅 시스템
- [layout-json.md](../frontend/layout-json.md) - 레이아웃 JSON 스키마
- [components.md](../frontend/components.md) - 컴포넌트 개발 규칙
+393
View File
@@ -0,0 +1,393 @@
# 메뉴 시스템
> G7의 메뉴 권한 시스템과 메뉴 시더 작성 규칙을 설명합니다.
---
## TL;DR (5초 요약)
```text
1. 구조: User → Role → role_menus 피벗 → Menu
2. 권한: MenuPermissionType (read, write, delete)
3. 모든 메뉴: role_menus에 명시적 역할 권한 필요 (코어/확장 구분 없음)
4. 자동 부여: 메뉴 생성 시 관리자 역할 + 생성자/설치자 역할 자동 부여
5. 시더: Menu::create() + grantAdminRoleToMenus() 패턴
```
---
## 목차
1. [메뉴 권한 아키텍처](#메뉴-권한-아키텍처)
2. [role_menus 피벗 테이블](#role_menus-피벗-테이블)
3. [MenuPermissionType Enum](#menupermissiontype-enum)
4. [Menu 모델의 HasRoleBasedAccess 구현](#menu-모델의-hasrolebasedaccess-구현)
5. [메뉴 시더에서 권한 부여](#메뉴-시더에서-권한-부여)
6. [메뉴 권한 확인 방법](#메뉴-권한-확인-방법)
7. [권한 체계 요약](#권한-체계-요약)
---
## 메뉴 권한 아키텍처
G7에서 메뉴 권한은 **역할 기반(Role-based)**으로 관리됩니다.
```
User → Role → role_menus → Menu
(pivot)
```
### 코어 메뉴 vs 모듈 메뉴
| 메뉴 유형 | 식별 | 기본 정책 |
|----------|------|----------|
| 코어 메뉴 | `extension_type = 'core'` | role_menus에 명시적 역할 권한 필요 |
| 모듈 메뉴 | `extension_type = 'module'` | 확장 활성 상태 + 명시적 역할 권한 필요 |
| 플러그인 메뉴 | `extension_type = 'plugin'` | 확장 활성 상태 + 명시적 역할 권한 필요 |
| 사용자 생성 메뉴 | `extension_type = NULL` | role_menus에 명시적 역할 권한 필요 |
---
## role_menus 피벗 테이블
### 테이블 구조
```php
Schema::create('role_menus', function (Blueprint $table) {
$table->id();
$table->foreignId('role_id')->constrained()->cascadeOnDelete();
$table->foreignId('menu_id')->constrained()->cascadeOnDelete();
$table->enum('permission_type', ['read', 'write', 'delete'])->default('read');
$table->timestamps();
$table->unique(['role_id', 'menu_id', 'permission_type'], 'uk_role_menu_permission');
});
```
### 설계 원칙
- **레코드 존재 = 권한 허용**: `is_allowed` 컬럼 없이 레코드 존재 여부로 판단
- **복합 유니크 인덱스**: 동일 역할-메뉴에 여러 권한 타입 부여 가능
- **Cascade Delete**: 역할 또는 메뉴 삭제 시 자동 정리
---
## MenuPermissionType Enum
```php
// app/Enums/MenuPermissionType.php
enum MenuPermissionType: string
{
case Read = 'read';
case Write = 'write';
case Delete = 'delete';
public function label(): string
{
return match ($this) {
self::Read => '읽기/접근',
self::Write => '수정',
self::Delete => '삭제',
};
}
}
```
### 권한 타입 설명
| 타입 | 값 | 설명 |
|------|-----|------|
| Read | `read` | 메뉴 조회/접근 권한 |
| Write | `write` | 메뉴 관련 데이터 수정 권한 |
| Delete | `delete` | 메뉴 관련 데이터 삭제 권한 |
---
## Menu 모델의 HasRoleBasedAccess 구현
`Menu` 모델은 `HasRoleBasedAccess` 인터페이스를 구현하여 역할 기반 접근 제어를 지원합니다.
### 인터페이스 구현
```php
// app/Models/Menu.php
class Menu extends Model implements HasRoleBasedAccess
{
/**
* 접근 가능한 역할들 (권한 타입 포함)
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_menus')
->withPivot('permission_type')
->withTimestamps();
}
/**
* 특정 권한 타입을 가진 역할들 조회
*/
public function rolesWithPermission(BackedEnum|string $permissionType): BelongsToMany
{
$type = $permissionType instanceof BackedEnum
? $permissionType->value
: $permissionType;
return $this->belongsToMany(Role::class, 'role_menus')
->withPivot('permission_type')
->withTimestamps()
->wherePivot('permission_type', $type);
}
/**
* 역할 권한이 설정되어 있는지 확인
*/
public function hasRolePermissions(): bool
{
return $this->roles()->exists();
}
/**
* 리소스 소유자의 ID 반환
*/
public function getOwnerId(): ?int
{
return $this->created_by;
}
}
```
### scopeAccessibleBy 쿼리 스코프
```php
/**
* 사용자에게 접근 가능한 메뉴들만 조회하는 스코프
*
* 권한 체크 로직:
* 1. 관리자는 모든 메뉴 접근 가능
* 2. 코어/사용자 생성 메뉴: role_menus에 명시적 역할 권한 필요
* 3. 모듈/플러그인 메뉴: 확장이 활성화되어 있고 역할 권한이 있어야 접근 가능
*
* 메뉴 생성 시 관리자 역할 + 생성자/설치자 역할이 자동 부여되므로
* role_menus 레코드가 없는 메뉴는 누구에게도 보이지 않습니다.
*/
public function scopeAccessibleBy(Builder $query, User $user): Builder
{
if ($user->hasRole('admin')) {
return $query;
}
$userRoleIds = $user->roles()->pluck('roles.id')->toArray();
return $query->where(function (Builder $query) use ($userRoleIds) {
// 코어/사용자 생성 메뉴: 명시적 역할 권한 필요
$query->where(function (Builder $q) use ($userRoleIds) {
$q->where(function ($q2) {
$q2->whereNull('extension_type')
->orWhere('extension_type', 'core');
})
->whereHas('roles', function (Builder $roleQ) use ($userRoleIds) {
$roleQ->whereIn('roles.id', $userRoleIds)
->where('role_menus.permission_type', MenuPermissionType::Read->value);
});
});
})->orWhere(function (Builder $query) use ($userRoleIds) {
// 모듈/플러그인 메뉴 (확장이 활성화되어 있고 역할 권한이 있는 경우)
$query->whereIn('extension_type', ['module', 'plugin'])
->whereHas('roles', function (Builder $roleQ) use ($userRoleIds) {
$roleQ->whereIn('roles.id', $userRoleIds)
->where('role_menus.permission_type', MenuPermissionType::Read->value);
});
});
}
```
---
## 메뉴 시더에서 권한 부여
### 예시: EcommerceMenuSeeder
```php
<?php
namespace Modules\Sirsoft\Ecommerce\Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Menu;
use App\Models\Role;
use App\Models\Module;
use App\Enums\MenuPermissionType;
class EcommerceMenuSeeder extends Seeder
{
public function run(): void
{
$this->command->info('이커머스 메뉴 생성을 시작합니다.');
$module = Module::where('identifier', 'sirsoft-ecommerce')->first();
// 메뉴 생성
$ecommerceMenu = Menu::create([
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'slug' => 'sirsoft-ecommerce',
'url' => '/admin/sirsoft-ecommerce',
'icon' => 'fa-shopping-cart',
'module_id' => $module->id,
]);
// 권한 부여
$this->grantMenuPermissions($module->id);
$this->command->info('이커머스 메뉴가 생성되었습니다.');
}
/**
* 역할에 메뉴 권한 부여
*/
private function grantMenuPermissions(int $moduleId): void
{
$adminRole = Role::where('identifier', 'admin')->first();
$managerRole = Role::where('identifier', 'sirsoft-ecommerce.manager')->first();
$ecommerceMenus = Menu::where('module_id', $moduleId)->get();
foreach ($ecommerceMenus as $menu) {
// 관리자: 모든 권한
$adminRole->menus()->attach($menu->id, [
'permission_type' => MenuPermissionType::Read->value,
]);
$adminRole->menus()->attach($menu->id, [
'permission_type' => MenuPermissionType::Write->value,
]);
$adminRole->menus()->attach($menu->id, [
'permission_type' => MenuPermissionType::Delete->value,
]);
// 매니저: 읽기/쓰기 권한만
if ($managerRole) {
$managerRole->menus()->attach($menu->id, [
'permission_type' => MenuPermissionType::Read->value,
]);
$managerRole->menus()->attach($menu->id, [
'permission_type' => MenuPermissionType::Write->value,
]);
}
}
$this->command->info("역할에 {$ecommerceMenus->count()}개의 메뉴 권한을 부여했습니다.");
}
}
```
### syncWithoutDetaching 사용 (기존 권한 유지)
```php
// 기존 권한을 유지하면서 새 권한 추가
$role->menus()->syncWithoutDetaching([
$menuId => ['permission_type' => 'read'],
]);
```
---
## 메뉴 권한 확인 방법
### 1. User 모델에서 확인
```php
// 기본 (read 권한)
$user->hasMenuPermission($menuId);
// 특정 권한 타입
$user->hasMenuPermission($menuId, 'write');
$user->hasMenuPermission($menuId, MenuPermissionType::Delete);
```
### 2. 쿼리 스코프로 필터링
```php
// 사용자가 접근 가능한 메뉴 조회
$accessibleMenus = Menu::accessibleBy($user)->get();
// 계층 구조와 함께 조회
$accessibleMenus = Menu::accessibleBy($user)
->whereNull('parent_id')
->with(['children' => function ($query) use ($user) {
$query->accessibleBy($user);
}])
->get();
```
### 3. Role 모델에서 확인
```php
// 역할에 메뉴 권한 부여
$role->menus()->attach($menuId, ['permission_type' => 'read']);
// 역할의 모든 메뉴 조회
$role->menus()->get();
// 특정 권한 타입의 메뉴만 조회
$role->menus()->wherePivot('permission_type', 'write')->get();
```
---
## 권한 체계 요약
### 권한 체크 흐름
```
┌─────────────────────────────────────────────────────────────┐
│ 1. 관리자(admin) 역할 확인 │
│ → admin이면 모든 메뉴 접근 허용 │
├─────────────────────────────────────────────────────────────┤
│ 2. 코어/사용자 생성 메뉴 (extension_type = 'core' 또는 NULL)│
│ → role_menus에 명시적 역할 권한 필요 │
│ → 메뉴 생성 시 관리자+생성자 역할 자동 부여 │
├─────────────────────────────────────────────────────────────┤
│ 3. 모듈/플러그인 메뉴 (extension_type = 'module'/'plugin') │
│ → 확장이 활성화(active) 상태여야 함 │
│ → role_menus에 명시적 권한 필요 │
└─────────────────────────────────────────────────────────────┘
```
### 권한 타입별 정리
| 권한 타입 | 용도 | 예시 |
|----------|------|------|
| `read` | 메뉴 표시, 페이지 접근 | 네비게이션 표시 |
| `write` | 데이터 생성/수정 | 상품 등록, 수정 |
| `delete` | 데이터 삭제 | 상품 삭제 |
### 동적 메뉴 보존
모듈/플러그인이 런타임에 동적으로 생성한 메뉴(예: 게시판 모듈의 개별 게시판 메뉴)는 확장 업데이트 시 자동으로 보존됩니다.
- `cleanupStaleMenus()`/`cleanupStalePermissions()`의 **자동 호출은 폐기**되었습니다
- 정적 메뉴/권한의 추가·수정은 업데이트 시 자동 동기화됩니다
- 정적 메뉴/권한을 **제거**해야 하는 경우, UpgradeStep에서 cleanup helper를 명시적으로 호출하세요
- 상세: [extension-update-system.md](./extension-update-system.md) "정적 메뉴/권한 제거 시 cleanup 사용 예시" 참조
### Deprecated 항목
다음 항목들은 더 이상 사용하지 않습니다:
| 항목 | 대체 방법 |
|------|----------|
| `menu_permissions` 테이블 | `role_menus` 피벗 테이블 |
| `MenuPermission` 모델 | `Role::menus()` 관계 |
| `is_allowed` 컬럼 | 레코드 존재 여부로 판단 |
| `User::menuPermissions()` | `User::hasMenuPermission()` |
| `module_id` 컬럼 | `extension_type` + `extension_identifier` |
| `module_identifier` 컬럼 | `extension_identifier` |
---
## 관련 문서
- [permissions.md](./permissions.md) - 권한 시스템 (Role, Permission, 리소스 레벨 권한)
- [module-basics.md](./module-basics.md) - 모듈 기본 구조
- [index.md](./index.md) - 확장 시스템 인덱스
+483
View File
@@ -0,0 +1,483 @@
# 모듈 프론트엔드 에셋 시스템
> 이 문서는 G7의 모듈 프론트엔드 에셋 로딩 시스템을 다룹니다.
---
## TL;DR (5초 요약)
```text
1. module.json에 에셋 매니페스트 정의 (js, css, loading strategy)
2. Vite IIFE 빌드로 dist/에 번들 생성
3. TemplateApp 초기화 시 자동 로드 (global 전략)
4. 핸들러 네이밍: {module-identifier}.{handler-name}
5. 빌드 명령: php artisan module:build [identifier] (기본: _bundled, --active로 활성)
```
---
## 목차
- [개요](#개요)
- [에셋 매니페스트 스키마](#에셋-매니페스트-스키마)
- [모듈 프론트엔드 구조](#모듈-프론트엔드-구조)
- [핸들러 등록](#핸들러-등록)
- [빌드 및 배포](#빌드-및-배포)
- [에셋 로딩 전략](#에셋-로딩-전략)
- [외부 라이브러리](#외부-라이브러리)
- [관련 문서](#관련-문서)
---
## 개요
모듈/플러그인은 자체 프론트엔드 에셋(JS, CSS, 이미지, 폰트 등)을 포함할 수 있습니다.
이 시스템은 활성화된 모듈의 에셋을 동적으로 로드하여 ActionDispatcher에 핸들러를 등록합니다.
### 작동 원리
```
1. admin.blade.php 렌더링
└─ window.G7Config.moduleAssets 주입
2. TemplateApp.init()
└─ ModuleAssetLoader.loadActiveExtensionAssets()
├─ CSS 로드 (병렬)
└─ JS 로드 (순차)
└─ 각 모듈의 initModule() 실행
└─ ActionDispatcher.registerHandler()
3. 레이아웃 렌더링
└─ 모듈 핸들러 사용 가능
```
---
## 에셋 매니페스트 스키마
### module.json (통합 스키마)
모듈 루트에 `module.json` 파일을 생성합니다. 메타데이터와 에셋 설정이 하나의 파일에 통합되어 있습니다.
```json
{
"identifier": "sirsoft-ecommerce",
"vendor": "sirsoft",
"name": {
"ko": "이커머스",
"en": "Ecommerce"
},
"version": "1.0.0",
"description": {
"ko": "상품 및 주문 관리를 위한 이커머스 모듈",
"en": "E-commerce module for product and order management"
},
"g7_version": ">=1.0.0",
"dependencies": {
"modules": {},
"plugins": {}
},
"github_url": null,
"github_changelog_url": null,
"assets": {
"js": {
"entry": "resources/js/index.ts",
"output": "dist/js/module.iife.js"
},
"css": {
"entry": "resources/css/main.css",
"output": "dist/css/module.css"
},
"handlers": true,
"static": "resources/assets/"
},
"loading": {
"strategy": "global",
"priority": 100
}
}
```
> **참고**: `identifier`, `vendor`는 디렉토리명에서 자동 추론되므로 생략 가능합니다.
> `name`, `version`, `description`은 AbstractModule에서 자동 파싱됩니다.
### 스키마 설명
#### 메타데이터 필드
| 필드 | 타입 | 필수 | 설명 |
|------|------|------|------|
| `identifier` | `string` | 선택 | 모듈 식별자 (디렉토리명에서 자동 추론) |
| `vendor` | `string` | 선택 | 벤더명 (identifier에서 자동 추론) |
| `name` | `string\|object` | 필수 | 모듈명 (다국어: `{"ko": "...", "en": "..."}`) |
| `version` | `string` | 필수 | 시맨틱 버전 (예: `1.0.0`) |
| `description` | `string\|object` | 필수 | 모듈 설명 (다국어 지원) |
| `g7_version` | `string` | 선택 | 그누보드7 코어 버전 제약 (예: `>=1.0.0`) |
| `dependencies` | `object` | 선택 | 모듈/플러그인 의존성 |
| `github_url` | `string\|null` | 선택 | GitHub 저장소 URL (업데이트 감지용) |
| `github_changelog_url` | `string\|null` | 선택 | GitHub 변경 이력 URL |
#### 에셋 필드
| 필드 | 설명 |
|------|------|
| `assets.js.entry` | JS 소스 엔트리 포인트 |
| `assets.js.output` | 빌드된 JS 출력 경로 |
| `assets.css.entry` | CSS 소스 엔트리 포인트 |
| `assets.css.output` | 빌드된 CSS 출력 경로 |
| `assets.handlers` | 핸들러 포함 여부 |
| `assets.static` | 정적 에셋 소스 디렉토리 |
| `loading.strategy` | 로딩 전략 (global, layout, lazy) |
| `loading.priority` | 로드 우선순위 (낮을수록 먼저) |
---
## 모듈 프론트엔드 구조
### 디렉토리 구조
```
modules/_bundled/sirsoft-ecommerce/
├── module.json ← 에셋 매니페스트
├── package.json ← npm 패키지 정의
├── vite.config.ts ← Vite 빌드 설정
├── tsconfig.json ← TypeScript 설정
├── dist/ ← 빌드 출력 (git ignore)
│ ├── js/module.iife.js
│ ├── css/module.css
│ └── assets/
│ ├── fonts/
│ └── images/
├── resources/
│ ├── js/ ← JS 소스
│ │ ├── index.ts
│ │ ├── types.ts
│ │ └── handlers/
│ │ ├── index.ts
│ │ └── updateProductField.ts
│ ├── css/main.css ← CSS 소스
│ └── assets/ ← 정적 에셋 소스
│ ├── fonts/
│ └── images/
└── ...
```
### package.json
```json
{
"name": "sirsoft-ecommerce",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite build --watch",
"build": "vite build"
},
"devDependencies": {
"typescript": "^5.0.0",
"vite": "^6.0.0"
}
}
```
### vite.config.ts
```typescript
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, 'resources/js/index.ts'),
name: 'SirsoftEcommerce',
fileName: 'module',
formats: ['iife'],
},
outDir: 'dist',
rollupOptions: {
output: {
entryFileNames: 'js/[name].iife.js',
assetFileNames: (assetInfo) => {
if (assetInfo.name?.endsWith('.css')) {
return 'css/[name][extname]';
}
return 'assets/[name][extname]';
},
},
},
emptyOutDir: true,
minify: true,
sourcemap: true,
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'resources/js'),
},
},
});
```
---
## 핸들러 등록
### 모듈 엔트리 파일 (index.ts)
```typescript
import '../css/main.css';
import { handlerMap } from './handlers';
const MODULE_IDENTIFIER = 'sirsoft-ecommerce';
export function initModule(): void {
const registerHandlers = () => {
const actionDispatcher = (window as any).G7Core?.getActionDispatcher?.();
if (actionDispatcher) {
Object.entries(handlerMap).forEach(([name, handler]) => {
const fullName = `${MODULE_IDENTIFIER}.${name}`;
actionDispatcher.registerHandler(fullName, handler);
});
console.log(`[Module:${MODULE_IDENTIFIER}] Handlers registered`);
} else {
// ActionDispatcher 초기화 대기
setTimeout(registerHandlers, 100);
}
};
if (document.readyState === 'complete') {
registerHandlers();
} else {
window.addEventListener('load', registerHandlers);
}
}
// IIFE 빌드 시 즉시 실행
initModule();
```
### 핸들러 정의
```typescript
// handlers/updateProductField.ts
import type { ActionContext } from '@/types';
interface UpdateProductFieldParams {
productId: string | number;
field: string;
value: string | number | boolean;
stateKey?: string;
}
export function updateProductFieldHandler(
params: UpdateProductFieldParams,
context: ActionContext
): void {
const { productId, field, value, stateKey = 'products' } = params;
// setState를 통해 상태 업데이트
if (context.setState) {
context.setState({
[stateKey]: {
_modified: {
[productId]: { [field]: value }
}
}
});
}
}
// handlers/index.ts
import { updateProductFieldHandler } from './updateProductField';
import { updateOptionFieldHandler } from './updateOptionField';
import type { ActionHandler } from '@/types';
export const handlerMap: Record<string, ActionHandler> = {
updateProductField: updateProductFieldHandler,
updateOptionField: updateOptionFieldHandler,
};
```
### 레이아웃에서 핸들러 사용
```json
{
"component": "Input",
"props": {
"type": "number",
"value": "{{row.stock_quantity}}"
},
"events": {
"onBlur": {
"handler": "sirsoft-ecommerce.updateProductField",
"params": {
"productId": "{{row.id}}",
"field": "stock_quantity",
"value": "{{$event.target.value}}"
}
}
}
}
```
---
## 빌드 및 배포
### Artisan 커맨드
```bash
# _bundled에서 빌드 (기본값)
php artisan module:build sirsoft-ecommerce
# 모든 _bundled 모듈 빌드
php artisan module:build --all
# 프로덕션 빌드 (_bundled)
php artisan module:build sirsoft-ecommerce --production
# 파일 감시 모드 (활성 디렉토리에서 자동 실행)
php artisan module:build sirsoft-ecommerce --watch
# 활성 디렉토리에서 빌드
php artisan module:build sirsoft-ecommerce --active
# 빌드 후 활성 디렉토리 반영
php artisan module:update sirsoft-ecommerce
```
### npm 스크립트
```bash
# 모듈 디렉토리에서 직접 실행
cd modules/_bundled/sirsoft-ecommerce
npm install
npm run build
# 개발 모드 (파일 감시)
npm run dev
```
### 에셋 서빙 API
빌드된 에셋은 다음 API를 통해 서빙됩니다:
```
GET /api/modules/assets/{identifier}/{path}
예시:
/api/modules/assets/sirsoft-ecommerce/dist/js/module.iife.js
/api/modules/assets/sirsoft-ecommerce/dist/css/module.css
```
---
## 에셋 로딩 전략
### global (기본값)
앱 초기화 시 자동으로 로드됩니다.
```json
{
"loading": {
"strategy": "global",
"priority": 100
}
}
```
- TemplateApp.init()에서 자동 로드
- 모든 페이지에서 핸들러 사용 가능
- 우선순위(priority)가 낮을수록 먼저 로드
### layout (향후 지원)
특정 레이아웃에서만 로드됩니다.
```json
{
"loading": {
"strategy": "layout"
}
}
```
- 레이아웃의 scripts 섹션에서 명시적 로드
- 해당 레이아웃 진입 시 로드
### lazy (향후 지원)
필요할 때 동적으로 로드됩니다.
```json
{
"loading": {
"strategy": "lazy"
}
}
```
- 핸들러 호출 시점에 로드
- 초기 로딩 시간 최적화
---
## 외부 라이브러리
외부 CDN 스크립트를 조건부로 로드할 수 있습니다.
### module.json 설정
```json
{
"assets": {
"external": [
{
"src": "https://cdn.example.com/chart.js",
"id": "chartjs-cdn",
"if": "{{_global.settings.useCharts}}"
}
]
}
}
```
### 레이아웃 scripts 섹션
```json
{
"scripts": [
{
"src": "https://cdn.example.com/lib.js",
"id": "external-lib",
"if": "{{_global.modules['sirsoft-ecommerce'].useExternalLib}}",
"async": true
}
]
}
```
---
## AbstractModule 에셋 메서드
AbstractModule은 에셋 관련 헬퍼 메서드를 제공합니다:
| 메서드 | 설명 |
|--------|------|
| `getAssets()` | module.json의 assets 섹션 반환 |
| `getAssetLoadingConfig()` | loading 설정 반환 (strategy, priority) |
| `hasAssets()` | 에셋 정의 존재 여부 |
| `getBuiltAssetPaths()` | 빌드된 에셋 경로 반환 (js, css) |
---
## 관련 문서
- [module-basics.md](./module-basics.md) - 모듈 개발 기초
- [hooks.md](./hooks.md) - 훅 시스템 (핸들러와 연계)
- [module-commands.md](./module-commands.md) - 모듈 Artisan 커맨드
- [../frontend/components.md](../frontend/components.md) - 컴포넌트 핸들러 호출
+629
View File
@@ -0,0 +1,629 @@
# 모듈 개발 기초
> 이 문서는 G7의 모듈 개발 기초를 다룹니다.
---
## TL;DR (5초 요약)
```text
1. 디렉토리: vendor-module (예: sirsoft-ecommerce)
2. 네임스페이스: Modules\Vendor\Module\ (예: Modules\Sirsoft\Ecommerce\)
3. AbstractModule 상속 권장 (ModuleInterface 직접 구현 가능)
4. 필수: module.json (메타데이터 SSoT), Module.php, composer.json, routes/admin.json
5. getName()/getVersion()/getDescription()은 module.json에서 자동 파싱 (하드코딩 불필요)
```
---
## 목차
- [모듈 네이밍 규칙](#모듈-네이밍-규칙)
- [AbstractModule 상속 (권장)](#abstractmodule-상속-권장)
- [ModuleInterface 직접 구현 (레거시)](#moduleinterface-직접-구현-레거시)
- [composer.json 작성법](#composerjson-모듈)
- [모듈 디렉토리 구조](#모듈-디렉토리-구조)
- [관련 문서](#관련-문서)
---
## 모듈 네이밍 규칙
### 디렉토리명
`vendor-module` 형식 (GitHub 스타일)
- 소문자 사용
- 하이픈(-): vendor와 module 구분
- 언더스코어(_): 모듈명 내 단어 구분 (선택적)
- 예: `sirsoft-ecommerce`, `sirsoft-order_management`, `johndoe-blog`
### 네임스페이스
`Modules\Vendor\Module\` 형식
- PascalCase 사용
- 백슬래시(\) 구분
- 예: `Modules\Sirsoft\Ecommerce\`, `Modules\Sirsoft\OrderManagement\`
### 디렉토리명 → 네임스페이스 변환 규칙
```text
필수: 변환 규칙 이해
하이픈(-) → 네임스페이스 구분자(\)
언더스코어(_) → PascalCase 결합
예시:
sirsoft-ecommerce → Sirsoft\Ecommerce
sirsoft-order_management → Sirsoft\OrderManagement
vendor-my_module_name → Vendor\MyModuleName
```
### Composer 패키지명
`modules/vendor-module`
- 예: `modules/sirsoft-ecommerce`, `modules/sirsoft-order_management`
### 네이밍 요약표
| 항목 | 형식 | 예시 |
|------|------|------|
| 디렉토리명 | `vendor-module` | `sirsoft-ecommerce`, `sirsoft-order_management` |
| 네임스페이스 | `Modules\Vendor\Module\` | `Modules\Sirsoft\Ecommerce\`, `Modules\Sirsoft\OrderManagement\` |
| Composer 패키지명 | `modules/vendor-module` | `modules/sirsoft-ecommerce`, `modules/sirsoft-order_management` |
### 식별자 검증 규칙
모듈/플러그인/템플릿 공통 식별자 검증 규칙은 [extension-manager.md](./extension-manager.md#식별자-검증-규칙-validextensionidentifier)를 참조하세요.
---
## AbstractModule 상속 (권장)
모듈 개발자는 `AbstractModule`을 상속받아 필수 메서드만 구현하면 됩니다.
`getIdentifier()`와 `getVendor()`는 디렉토리명에서 자동으로 추론됩니다.
### manifest 자동 파싱 메서드 (오버라이드 불필요)
`module.json`에서 자동으로 값을 읽어오는 메서드입니다. 하드코딩 오버라이드가 불필요합니다.
| 메서드 | 반환 타입 | 소스 (module.json) | 기본값 |
|--------|----------|-------------------|--------|
| `getName()` | `string\|array` | `name` | identifier |
| `getVersion()` | `string` | `version` | `'0.0.0'` |
| `getDescription()` | `string\|array` | `description` | `''` |
| `getRequiredCoreVersion()` | `?string` | `g7_version` | `null` |
| `getLicense()` | `?string` | `license` | `null` |
| `getGithubUrl()` | `?string` | `github_url` | `null` |
| `getAssets()` | `array` | `assets` | `[]` |
| `getAssetLoadingConfig()` | `array` | `loading` | strategy: global, priority: 100 |
> **`license` 필드**: `module.json`에 `"license": "MIT"` 등의 라이선스 정보를 포함합니다. 이 값은 API 리소스의 `license` 필드로 노출됩니다. 또한 각 모듈 루트에 `LICENSE` 파일을 포함하여 라이선스 전문을 제공해야 합니다.
### 자동 추론 메서드 (final - 오버라이드 불가)
| 메서드 | 반환 타입 | 설명 |
|--------|----------|------|
| `getIdentifier()` | `string` | 디렉토리명에서 자동 추론 (예: `sirsoft-ecommerce`) |
| `getVendor()` | `string` | 디렉토리명에서 자동 추론 (예: `sirsoft`) |
### 기본값 제공 메서드 (필요시 오버라이드)
| 메서드 | 기본값 | 설명 |
|--------|--------|------|
| `install()` | `true` | 설치 로직 |
| `uninstall()` | `true` | 제거 로직 |
| `activate()` | `true` | 활성화 로직 |
| `deactivate()` | `true` | 비활성화 로직 |
| `getDynamicTables()` | `[]` | 런타임 동적 생성 테이블 목록 (언인스톨 시 Manager가 삭제) |
| `getRoutes()` | 자동 탐지 | `src/routes/api.php`, `src/routes/web.php` |
| `getMigrations()` | 자동 탐지 | `database/migrations` 디렉토리 |
| `getViews()` | `[]` | 뷰 파일 |
| `getPermissions()` | `[]` | 권한 목록 (resource_route_key, owner_key, roles scope_type 지원) |
| `getRoles()` | `[]` | 역할 목록 |
| `getConfig()` | `[]` | 설정 |
| `getAdminMenus()` | `[]` | 관리자 메뉴 |
| `getHookListeners()` | `[]` | 훅 리스너 |
| `getDependencies()` | `[]` | 의존성 |
| `getMetadata()` | `[]` | 메타데이터 |
| `upgrades()` | `[]` | 업그레이드 스텝 (`upgrades/` 디렉토리 자동 발견) |
### 간결한 모듈 구현 예시
> **참고**: `getName()`, `getVersion()`, `getDescription()`은 `module.json`에서 자동 파싱되므로 오버라이드가 불필요합니다.
```php
<?php
namespace Modules\Sirsoft\Ecommerce;
use App\Extension\AbstractModule;
class Module extends AbstractModule
{
// getName(), getVersion(), getDescription()은 module.json에서 자동 파싱
// 별도 오버라이드 불필요
/**
* 역할 목록 (필요시 오버라이드)
*/
public function getRoles(): array
{
return [
[
'identifier' => 'sirsoft-ecommerce.manager',
'name' => [
'ko' => '이커머스 관리자',
'en' => 'Ecommerce Manager',
],
'description' => [
'ko' => '이커머스 모듈 관리 권한을 가진 역할',
'en' => 'Role with ecommerce module management permissions',
],
],
];
}
/**
* 권한 목록 (필요시 오버라이드)
*
* - resource_route_key: 라우트 파라미터명 (scope 체크용, 소유자 개념 없으면 생략)
* - owner_key: 모델의 소유자 식별 컬럼명 (scope 체크용, 소유자 개념 없으면 생략)
* - roles: 문자열 배열 또는 {role, scope_type} 객체 배열
*/
public function getPermissions(): array
{
return [
[
'identifier' => 'sirsoft-ecommerce.products.view',
'name' => [
'ko' => '상품 조회',
'en' => 'View Products',
],
'description' => [
'ko' => '상품 목록 및 상세 정보를 조회할 수 있습니다',
'en' => 'Can view product list and details',
],
'resource_route_key' => 'product', // 라우트 파라미터명
'owner_key' => 'created_by', // 소유자 컬럼
// roles에 scope_type 지정 가능 (null=전체, 'self'=본인, 'role'=소유역할)
'roles' => [
['role' => 'admin', 'scope_type' => null],
['role' => 'sirsoft-ecommerce.manager', 'scope_type' => 'role'],
],
],
[
'identifier' => 'sirsoft-ecommerce.products.create',
'name' => [
'ko' => '상품 생성',
'en' => 'Create Products',
],
'description' => [
'ko' => '새로운 상품을 생성할 수 있습니다',
'en' => 'Can create new products',
],
'resource_route_key' => 'product',
'owner_key' => 'created_by',
'roles' => ['admin'], // 문자열 배열도 허용 (scope_type=null 기본값)
],
[
'identifier' => 'sirsoft-ecommerce.orders.view',
'name' => [
'ko' => '주문 조회',
'en' => 'View Orders',
],
'description' => [
'ko' => '주문 목록 및 상세 정보를 조회할 수 있습니다',
'en' => 'Can view order list and details',
],
'resource_route_key' => 'order',
'owner_key' => 'user_id',
'roles' => ['admin', 'sirsoft-ecommerce.manager'],
],
[
'identifier' => 'sirsoft-ecommerce.categories.view',
'name' => [
'ko' => '카테고리 조회',
'en' => 'View Categories',
],
'description' => [
'ko' => '카테고리 목록을 조회할 수 있습니다',
'en' => 'Can view category list',
],
// resource_route_key/owner_key 생략 = 소유자 개념 없음 (scope 체크 스킵)
'roles' => ['admin'],
],
];
}
/**
* 관리자 메뉴 정의 (필요시 오버라이드)
*/
public function getAdminMenus(): array
{
return [
[
'name' => [
'ko' => '이커머스',
'en' => 'Ecommerce',
],
'slug' => 'ecommerce',
'url' => '/admin/ecommerce',
'icon' => 'fa-shopping-cart',
'order' => 20,
'children' => [
[
'name' => [
'ko' => '상품 관리',
'en' => 'Product Management',
],
'slug' => 'sirsoft-ecommerce-products',
'url' => '/admin/ecommerce/products',
'icon' => 'fa-box',
'order' => 1,
'permission' => 'sirsoft-ecommerce.products.view',
],
[
'name' => [
'ko' => '주문 관리',
'en' => 'Order Management',
],
'slug' => 'sirsoft-ecommerce-orders',
'url' => '/admin/ecommerce/orders',
'icon' => 'fa-receipt',
'order' => 2,
'permission' => 'sirsoft-ecommerce.orders.view',
],
],
],
];
}
/**
* 훅 리스너 목록 (필요시 오버라이드)
*/
public function getHookListeners(): array
{
return [
\Modules\Sirsoft\Ecommerce\Listeners\ProductCacheInvalidationListener::class,
\Modules\Sirsoft\Ecommerce\Listeners\OrderNotificationListener::class,
];
}
/**
* 모듈 메타데이터 (필요시 오버라이드)
*/
public function getMetadata(): array
{
return [
'author' => 'sirsoft',
'license' => 'MIT',
];
}
}
```
---
## ModuleInterface 직접 구현 (레거시)
> **참고**: 특별한 경우가 아니라면 `AbstractModule` 상속을 권장합니다.
`ModuleInterface`를 직접 구현할 경우, 모든 메서드를 직접 구현해야 합니다:
```php
<?php
namespace Modules\Sirsoft\Ecommerce;
use App\Contracts\Extension\ModuleInterface;
class Module implements ModuleInterface
{
public function getIdentifier(): string
{
return 'sirsoft-ecommerce';
}
public function getVendor(): string
{
return 'sirsoft';
}
// ... 모든 메서드 직접 구현 필요
}
```
---
## composer.json (모듈)
### 기본 구조
```json
{
"name": "modules/sirsoft-ecommerce",
"description": "E-commerce module for Gnuboard7 platform by sirsoft",
"type": "library",
"authors": [
{
"name": "sirsoft",
"email": "contact@sirsoft.com"
}
],
"require": {
"php": "^8.2"
},
"autoload": {
"psr-4": {
"Modules\\Sirsoft\\Ecommerce\\": "src/"
}
}
}
```
### 외부 패키지 의존성
모듈이 외부 Composer 패키지를 필요로 하는 경우, `require`에 추가합니다.
```json
{
"name": "modules/sirsoft-ecommerce",
"require": {
"php": "^8.2",
"stripe/stripe-php": "^13.0",
"intervention/image": "^3.0"
},
"autoload": {
"psr-4": {
"Modules\\Sirsoft\\Ecommerce\\": "src/"
}
}
}
```
```text
주의: 루트 composer.json에 모듈 패키지 추가 금지
모듈 설치 시 자동으로 composer install 실행 (Phase 4.5)
modules/{identifier}/vendor/ 디렉토리에 독립 설치
수동 설치: php artisan module:composer-install [identifier]
```
- `php`와 `ext-*` 패키지는 외부 의존성으로 간주되지 않음 (composer install 트리거 안 함)
- 설치된 패키지는 `vendor_autoloads`를 통해 런타임에 자동 로드됨
- 상세: [extension-manager.md](extension-manager.md) "Composer 의존성 관리" 참조
### Factory/Seeder 사용 시 추가 설정
```
필수: database/factories/ 또는 database/seeders/ 사용 시 autoload 등록
등록하지 않으면 테스트에서 "Class not found" 오류 발생
```
Factory 또는 Seeder를 사용하는 모듈은 **반드시** composer.json에 해당 경로를 등록해야 합니다:
```json
{
"name": "modules/sirsoft-ecommerce",
"description": "E-commerce module for Gnuboard7 platform by sirsoft",
"type": "library",
"version": "1.0.0",
"license": "MIT",
"autoload": {
"psr-4": {
"Modules\\Sirsoft\\Ecommerce\\": "src/",
"Modules\\Sirsoft\\Ecommerce\\Database\\Seeders\\": "database/seeders/",
"Modules\\Sirsoft\\Ecommerce\\Database\\Factories\\": "database/factories/"
}
},
"require": {
"php": "^8.2"
}
}
```
### autoload 설정 후 갱신 (필수)
composer.json 수정 후 반드시 autoload 갱신:
```bash
php artisan extension:update-autoload
```
---
## 모듈 디렉토리 구조
```
modules/_bundled/sirsoft-ecommerce/
├── module.json # 메타데이터 (이름, 버전, 설명 등 SSoT)
├── module.php # ModuleInterface 구현
├── LICENSE # 라이선스 전문 (MIT)
├── composer.json # 오토로딩 + 외부 패키지 의존성 설정
├── package.json # npm 패키지 정의 (에셋 모듈만)
├── vite.config.ts # Vite 빌드 설정 (에셋 모듈만)
├── tsconfig.json # TypeScript 설정 (에셋 모듈만)
├── vendor/ # Composer 의존성 (자동 생성, gitignore 대상)
├── dist/ # 프론트엔드 빌드 출력 (에셋 모듈만, gitignore 대상)
│ ├── js/module.iife.js
│ └── css/module.css
├── upgrades/ # 버전 업그레이드 스텝 (UpgradeStepInterface 구현)
│ └── Upgrade_1_1_0.php # 1.1.0 버전 업그레이드 로직
├── config/
│ └── ecommerce.php # 모듈 설정
├── database/
│ ├── factories/ # 테스트용 Factory
│ ├── migrations/ # 마이그레이션
│ └── seeders/ # 시더
│ ├── DatabaseSeeder.php # 메인 시더 (설치 + 조건부 샘플)
│ └── Sample/ # 샘플(개발용) 시더
├── lang/ # 다국어 파일 (PHP 배열)
│ ├── en/
│ └── ko/
├── resources/ # 리소스 파일
│ ├── js/ # 프론트엔드 JS 소스 (에셋 모듈만)
│ │ ├── index.ts # 엔트리 포인트
│ │ └── handlers/ # 커스텀 핸들러
│ ├── css/ # CSS 소스 (에셋 모듈만)
│ │ └── main.css
│ ├── lang/ # 프론트엔드 다국어 (JSON)
│ │ ├── ko.json # 한국어 프론트엔드 다국어
│ │ └── en.json # 영어 프론트엔드 다국어
│ ├── layouts/ # 레이아웃 JSON
│ │ ├── admin/ # admin 템플릿 레이아웃
│ │ └── user/ # user 템플릿 레이아웃 (선택)
│ ├── routes/ # 프론트엔드 라우트 정의
│ │ ├── admin.json # admin 템플릿 전용 라우트
│ │ └── user.json # user 템플릿 전용 라우트 (선택)
│ └── views/ # 뷰 파일 (Blade 템플릿 등)
├── src/
│ ├── Contracts/ # 인터페이스
│ ├── Http/ # HTTP 계층
│ │ ├── Controllers/ # 컨트롤러
│ │ │ └── Api/
│ │ │ └── Admin/
│ │ ├── Requests/ # FormRequest 클래스
│ │ └── Resources/ # API 리소스
│ ├── Listeners/ # 훅 리스너
│ ├── Models/ # 모델
│ ├── Providers/ # 프로바이더
│ ├── Repositories/ # 리포지토리
│ ├── Seo/ # SEO Sitemap 기여자, 캐시 무효화 리스너
│ ├── routes/ # 라우트 (src 하위)
│ │ ├── api.php
│ │ └── web.php
│ └── Services/ # 서비스
└── tests/ # 테스트 파일
├── Feature/ # 기능 테스트
└── Unit/ # 단위 테스트
```
### 디렉토리 설명
| 디렉토리 | 설명 |
|----------|------|
| `module.json` | 메타데이터 SSoT (이름, 버전, 설명, 의존성, 라이선스 등) |
| `module.php` | ModuleInterface 구현 (진입점) |
| `LICENSE` | 라이선스 전문 (MIT 등) — API 엔드포인트 `GET /api/admin/modules/{identifier}/license`로 제공 |
| `composer.json` | PSR-4 오토로딩 + 외부 패키지 의존성 설정 |
| `package.json` | npm 패키지 정의 (에셋 모듈만 해당) |
| `vite.config.ts` | Vite IIFE 빌드 설정 (에셋 모듈만 해당) |
| `vendor/` | Composer 의존성 디렉토리 (자동 생성, gitignore 대상) |
| `dist/` | 프론트엔드 빌드 출력 (에셋 모듈만 해당, gitignore 대상) |
| `config/` | 모듈별 설정 파일 |
| `database/factories/` | 테스트용 Factory (autoload 등록 필수) |
| `database/migrations/` | 데이터베이스 마이그레이션 |
| `database/seeders/` | 데이터베이스 시더 (autoload 등록 필수). 설치 시더는 루트, 샘플 시더는 `Sample/` 하위 |
| `lang/` | 백엔드 다국어 (PHP 배열) |
| `resources/js/` | 프론트엔드 JS/TS 소스 — 핸들러 정의 등 (에셋 모듈만 해당) |
| `resources/css/` | CSS 소스 (에셋 모듈만 해당) |
| `resources/lang/` | 프론트엔드 다국어 (JSON) |
| `resources/layouts/` | 레이아웃 JSON (admin/, user/ 하위) |
| `resources/routes/admin.json` | admin 템플릿 전용 프론트엔드 라우트 |
| `resources/routes/user.json` | user 템플릿 전용 프론트엔드 라우트 (선택) |
| `src/Http/Controllers/` | 컨트롤러 |
| `src/Http/Requests/` | FormRequest 클래스 |
| `src/Http/Resources/` | API 리소스 |
| `src/Listeners/` | 훅 리스너 |
| `src/Models/` | Eloquent 모델 |
| `src/Repositories/` | 리포지토리 |
| `src/Seo/` | SEO Sitemap 기여자, 캐시 무효화 리스너 |
| `src/Services/` | 비즈니스 로직 서비스 |
| `src/routes/` | API/Web 라우트 |
| `tests/` | 테스트 파일 |
---
## 번들 디렉토리 작업 규칙
```text
필수: 모듈 수정/개발은 _bundled 디렉토리에서만 작업
필수: _bundled 작업 완료 후 반영/검증은 업데이트 프로세스 사용
```
### 개발 워크플로우
```text
1. modules/_bundled/{identifier}/ 에서 코드 수정
2. _bundled에서 직접 테스트 실행으로 검증 (활성 디렉토리 복사 불필요)
3. module.json 버전 올리기
4. php artisan module:update {identifier} 로 활성 디렉토리에 프로덕션 반영
```
### _bundled 직접 테스트 실행
_bundled에서 바로 PHPUnit/Vitest 테스트를 실행할 수 있습니다. `tests/bootstrap.php`가 _bundled 코드를 활성 디렉토리보다 우선 로드합니다.
```bash
# 백엔드 테스트 (_bundled에서 직접 실행)
php vendor/bin/phpunit modules/_bundled/{identifier}/tests
php vendor/bin/phpunit --filter=TestName modules/_bundled/{identifier}/tests
# 프론트엔드 테스트
cd modules/_bundled/{identifier}
powershell -Command "npm run test:run"
```
> 상세: [testing-guide.md](../testing-guide.md) "_bundled 확장 직접 테스트" 참조
### 왜 활성 디렉토리 직접 수정이 금지되는가?
- 활성 디렉토리는 `.gitignore` 대상 → Git에 변경 기록 불가
- 다음 업데이트 시 `_bundled` 소스로 덮어쓰기 → 직접 수정 사항 유실
- 업데이트 프로세스 미수행 시 마이그레이션/권한 동기화/레이아웃 갱신 누락
### 예외: 초기 개발 (아직 _bundled에 미등록)
```text
✅ 허용: 신규 모듈 초기 개발 시 활성 디렉토리에서 직접 작업
전환점: _bundled에 최초 반영한 이후부터는 반드시 _bundled에서만 작업
```
> 상세: [extension-update-system.md](./extension-update-system.md) "번들 디렉토리 개발 워크플로우" 참조
---
## 코드 변경 시 버전/업그레이드 필수
```text
필수: 모듈 코드를 변경한 경우 버전을 올리고 필요 시 업그레이드 스텝을 작성해야 합니다.
버전 변경 없이 _bundled에 반영하면, 이미 설치된 환경에서 업데이트가 감지되지 않습니다.
```
### 필수 작업
1. **`module.json` 버전 올리기**: `version` 필드를 Semantic Versioning에 따라 증가
2. **`_bundled` 동기화**: `modules/_bundled/{identifier}/` 디렉토리에 변경 사항 반영
3. **업그레이드 스텝 작성** (조건부): DB 스키마/환경설정 구조/데이터 마이그레이션이 필요한 경우
### 업그레이드 스텝 작성 기준
| 변경 유형 | 업그레이드 스텝 필요 | 비고 |
|----------|-------------------|------|
| DB 스키마 변경 | ✅ (+ 마이그레이션) | 컬럼/테이블 구조 변경 |
| 환경설정 구조 변경 | ✅ (SettingsMigrator) | 설정 키 이름/구조 변경 |
| 기존 데이터 변환 | ✅ | 데이터 형식 변환, 기본값 |
| 권한/역할/메뉴 추가·수정 | ❌ (자동 동기화) | Module.php에서 정의 |
| 정적 권한/메뉴 제거 | ✅ (cleanup 명시 호출) | #135: 동적 메뉴/권한 보존 |
| 레이아웃 JSON 변경 | ❌ (자동 갱신) | refresh-layout에서 처리 |
| PHP 코드만 변경 | ❌ | 버전만 올리면 됨 |
> 상세: [extension-update-system.md](./extension-update-system.md) "개발자 버전 업데이트 가이드" 참조
---
## 관련 문서
- [index.md](./index.md) - 확장 시스템 개요
- [hooks.md](./hooks.md) - 훅 시스템
- [module-routing.md](./module-routing.md) - 모듈 라우트 규칙
- [module-layouts.md](./module-layouts.md) - 모듈 레이아웃 시스템
- [module-assets.md](./module-assets.md) - 모듈 프론트엔드 에셋 시스템
- [module-commands.md](./module-commands.md) - 모듈 Artisan 커맨드
- [module-i18n.md](./module-i18n.md) - 모듈 다국어
- [활동 로그 시스템](../backend/activity-log.md) - 활동 로그 Listener, DescriptionResolver, Per-Item Bulk 로깅 규칙
- [extension-update-system.md](./extension-update-system.md) - 확장 업데이트 시스템
- [permissions.md](./permissions.md) - 권한 시스템
- [menus.md](./menus.md) - 메뉴 시스템
+548
View File
@@ -0,0 +1,548 @@
# 모듈 Artisan 커맨드
> **관련 문서**: [index.md](index.md) | [module-basics.md](module-basics.md) | [module-routing.md](module-routing.md)
---
## TL;DR (5초 요약)
```text
1. 목록: php artisan module:list
2. 설치: php artisan module:install [identifier] (Composer 의존성 자동 설치 포함)
3. 활성화: php artisan module:activate [identifier]
4. 비활성화: php artisan module:deactivate [identifier]
5. Composer: php artisan module:composer-install [identifier] (수동 의존성 설치)
6. 삭제: php artisan module:uninstall [identifier] (--delete-data 시 vendor/ 삭제 포함)
```
---
## 목차
- [핵심 원칙](#핵심-원칙)
- [사용 가능한 커맨드](#사용-가능한-커맨드)
- [커맨드 구현 규칙](#커맨드-구현-규칙)
- [커맨드 테스트](#커맨드-테스트)
---
## 핵심 원칙
### 모듈 Artisan 커맨드 규칙
```
필수: 모듈 관련 모든 작업은 Artisan 커맨드로 수행
✅ 규칙: 직접 DB 조작 또는 파일 시스템 변경 금지
```
모듈의 설치, 활성화, 비활성화, 삭제 등 모든 생명주기 관리는 반드시 Artisan 커맨드를 통해 수행해야 합니다. 이를 통해:
- 일관된 상태 관리
- 적절한 이벤트 발생
- 권한/메뉴 등 연관 데이터 관리
- 로그 기록
---
## 사용 가능한 커맨드
### 모듈 관리 커맨드
#### 모듈 목록 조회
```bash
php artisan module:list
```
**옵션**:
- `--status=active`: 활성화된 모듈만 표시
- `--status=inactive`: 비활성화된 모듈만 표시
- `--status=uninstalled`: 미설치 모듈만 표시
**출력 예시**:
```
+--------------------+----------+---------+
| Identifier | Version | Status |
+--------------------+----------+---------+
| sirsoft-ecommerce | 1.0.0 | active |
| sirsoft-blog | 1.2.0 | inactive|
| vendor-sample | 0.1.0 | - |
+--------------------+----------+---------+
```
#### 모듈 설치
```bash
php artisan module:install [identifier]
```
**수행 작업**:
- `_pending/_bundled` 디렉토리에서 활성 디렉토리로 복사 (ExtensionPendingHelper)
- `modules` 테이블에 모듈 등록
- 역할(Role) 등록
- 권한(Permission) 등록
- 메뉴(Menu) 등록
- 마이그레이션 실행 (있는 경우)
- 시더 실행 (있는 경우)
- Composer 의존성 설치 (외부 패키지가 있는 경우, Phase 4.5)
**예시**:
```bash
php artisan module:install sirsoft-ecommerce
```
#### 모듈 활성화
```bash
php artisan module:activate [identifier]
```
**수행 작업**:
- `modules.status`를 `active`로 변경
- soft deleted된 레이아웃 복원
- 모듈 레이아웃 등록 (admin 템플릿에)
- 모듈의 라우트 활성화
- 모듈의 훅 리스너 활성화
- **템플릿 언어/routes 캐시 무효화**
- **extension_cache_version 증가 (프론트엔드 캐시 무효화)**
#### 모듈 비활성화
```bash
php artisan module:deactivate [identifier]
```
**수행 작업**:
- `modules.status`를 `inactive`로 변경
- 모듈 레이아웃 soft delete
- 모듈의 라우트 비활성화
- 모듈의 훅 리스너 비활성화
- **템플릿 언어/routes 캐시 무효화**
- **extension_cache_version 증가 (프론트엔드 캐시 무효화)**
#### 모듈 삭제
```bash
php artisan module:uninstall [identifier]
```
**옵션**:
- `--force`: 확인 프롬프트 없이 즉시 삭제
- `--delete-data`: 데이터도 함께 삭제 (동적 테이블 + 마이그레이션 롤백 + 스토리지)
**수행 작업**:
- 확인 프롬프트 표시 (--force 미사용 시)
- `--delete-data` 사용 시 (트랜잭션 외부, DDL):
- `getDynamicTables()` 반환 테이블 삭제 (Manager가 처리)
- 마이그레이션 롤백 (정적 테이블 삭제)
- 모듈 스토리지 디렉토리 삭제 (`storage/app/modules/{identifier}/`)
- Composer vendor/ 디렉토리 및 composer.lock 삭제
- 역할(Role) 삭제
- 권한(Permission) 삭제
- 메뉴(Menu) 삭제
- 레이아웃(Layout) 영구 삭제
- 활성 디렉토리 삭제 (`_bundled` 원본은 보존)
- `modules` 테이블에서 완전 삭제 (hard delete)
- **템플릿 언어/routes 캐시 무효화**
- **extension_cache_version 증가 (프론트엔드 캐시 무효화)**
**예시**:
```bash
# 확인 프롬프트 표시
php artisan module:uninstall sirsoft-ecommerce
# 강제 삭제
php artisan module:uninstall sirsoft-ecommerce --force
```
#### 모듈 Composer 의존성 설치
```bash
php artisan module:composer-install [identifier]
```
**옵션**:
- `--all`: 모든 설치된 모듈의 Composer 의존성 설치
- `--no-dev`: dev 의존성 제외
**예시**:
```bash
# 특정 모듈 의존성 설치
php artisan module:composer-install sirsoft-ecommerce
# 모든 모듈 의존성 설치
php artisan module:composer-install --all
# dev 의존성 제외
php artisan module:composer-install sirsoft-ecommerce --no-dev
```
**수행 작업**:
- 모듈의 `composer.json`에 외부 패키지(`require`)가 있는지 확인
- `modules/{identifier}/` 디렉토리에서 `composer install` 실행
- `modules/{identifier}/vendor/` 디렉토리 생성
- 오토로드 캐시 파일 갱신 (`vendor_autoloads` 반영)
**사용 시점**:
- 모듈 설치 시 자동 실행되지만, 수동으로 재설치가 필요한 경우
- vendor/ 디렉토리가 손상되거나 삭제된 경우
- 새로운 패키지를 composer.json에 추가한 후
#### 모듈 업데이트 확인
```bash
php artisan module:check-updates [identifier?]
```
**인수**:
- `identifier` (선택): 특정 모듈만 확인
**기능**:
- **전체 확인** (인수 없음): 설치된 모든 모듈의 업데이트 가용 여부를 테이블로 출력
- 감지 우선순위: GitHub > `_bundled` (2단계, `_pending` 미참여)
- DB에 `update_available`, `latest_version`, `update_source` 갱신
- **단일 확인** (인수 있음): 특정 모듈의 업데이트 가용 여부 확인
- `checkModuleUpdate()`는 DB 갱신 안 함 → 커맨드에서 `updateByIdentifier()` 직접 호출
**예시**:
```bash
# 모든 모듈 업데이트 확인
php artisan module:check-updates
# 특정 모듈만 확인
php artisan module:check-updates sirsoft-ecommerce
```
#### 모듈 업데이트
```bash
php artisan module:update [identifier] [--force]
```
**인수**:
- `identifier` (필수): 업데이트할 모듈 식별자
**옵션**:
- `--force`: 버전 비교 없이 강제 업데이트 (파일 손상, 수동 수정 복원 시 사용)
**수행 작업**:
- 업데이트 가용 여부 확인 (없으면 info + SUCCESS, `--force` 시 무시하고 진행)
- 확인 프롬프트 → 업데이트 실행
- 상태 가드 확인 → 백업 → status: Updating → 파일 교체 → 마이그레이션 → 업그레이드 스텝 → 복원
- 실패 시 백업 복원 안내
**예시**:
```bash
php artisan module:update sirsoft-ecommerce
php artisan module:update sirsoft-ecommerce --force # 강제 재설치
```
#### 모듈 캐시 초기화
```bash
php artisan module:cache-clear
```
**옵션**:
- `[identifier]`: 특정 모듈만 캐시 삭제
**예시**:
```bash
# 모든 모듈 캐시 삭제
php artisan module:cache-clear
# 특정 모듈 캐시만 삭제
php artisan module:cache-clear sirsoft-ecommerce
```
#### 모듈 프론트엔드 에셋 빌드
```bash
php artisan module:build [identifier]
```
> **기본 빌드 경로**: `_bundled` 디렉토리. 빌드 결과물은 빌드 경로 내에만 남음.
> 활성 디렉토리 반영은 `module:update` 커맨드로만 수행.
**옵션**:
- `--all`: 모든 모듈의 에셋 빌드 (_bundled 기준, --active 시 활성 기준)
- `--watch`: 파일 변경 감시 모드 (자동으로 활성 디렉토리 사용)
- `--production`: 프로덕션 최적화 빌드
- `--active`: 활성 디렉토리에서 빌드 (_bundled 대신)
**예시**:
```bash
# _bundled에서 빌드 (기본값)
php artisan module:build sirsoft-ecommerce
# 모든 _bundled 모듈 빌드
php artisan module:build --all
# 프로덕션 빌드 (_bundled)
php artisan module:build sirsoft-ecommerce --production
# 파일 감시 모드 (활성 디렉토리에서 자동 실행)
php artisan module:build sirsoft-ecommerce --watch
# 활성 디렉토리에서 빌드
php artisan module:build sirsoft-ecommerce --active
# 빌드 후 활성 디렉토리 반영
php artisan module:update sirsoft-ecommerce
```
**수행 작업**:
- 빌드 경로 결정: _bundled 우선 → 활성 폴백 (--active 시 활성만)
- npm 의존성 설치 (node_modules 없는 경우)
- Vite를 통한 IIFE 번들 빌드
- `dist/js/module.iife.js` 및 `dist/css/module.css` 생성
- 빌드 결과 파일 크기 출력
- **extension_cache_version 증가 (프론트엔드 캐시 무효화)**
- 주의: `--watch` 모드에서는 캐시 버전이 증가하지 않음
**참고**: [module-assets.md](./module-assets.md) 문서에서 에셋 빌드 설정 상세 참조
#### 모듈 시더 실행
```bash
php artisan module:seed [identifier]
```
**옵션**:
- `--class=SeederClass`: 특정 시더 클래스만 실행
- `--sample`: 샘플 데이터 시더도 함께 실행 (기본: 설치 시더만)
- `--count=key=value`: 시더에 카운트 옵션 전달 (반복 가능)
- `--force`: 프로덕션 환경에서 강제 실행
**예시**:
```bash
# 단일 모듈 시더 실행 (설치 시더만)
php artisan module:seed sirsoft-ecommerce
# 설치 + 샘플 시더 실행
php artisan module:seed sirsoft-ecommerce --sample
# 모든 활성 모듈 시더 실행
php artisan module:seed
# 특정 시더 클래스 실행
php artisan module:seed sirsoft-ecommerce --class=Sample\\ProductSeeder
# 샘플 + 카운트 옵션
php artisan module:seed sirsoft-ecommerce --sample --count=products=1000
# 프로덕션 환경에서 강제 실행
php artisan module:seed sirsoft-ecommerce --force
```
**수행 작업**:
- 활성화된 모듈만 실행 가능 (비활성 모듈은 에러)
- `modules/{identifier}/database/seeders/DatabaseSeeder.php` 실행
- 기본 실행 시 설치 필수 시더만 실행, `--sample` 옵션 시 Sample/ 하위 시더도 실행
- `--class` 옵션 사용 시 해당 시더만 실행
- `--sample` 옵션은 `HasSampleSeeders` 트레이트를 통해 시더에 전파
**주의사항**:
- 활성화되지 않은 모듈은 시더 실행 불가
- 프로덕션 환경에서는 `--force` 옵션 필수
- 샘플 시더는 `database/seeders/Sample/` 하위 디렉토리에 위치
---
## 커맨드 구현 규칙
### 1. 다국어 메시지 필수
```php
// ✅ DO: 다국어 메시지 사용
$this->info(__('modules.commands.install.success', ['module' => $identifier]));
// ❌ DON'T: 하드코딩 메시지
$this->info('모듈 설치 성공');
```
### 2. 로그 기록 필수
```php
use Illuminate\Support\Facades\Log;
// 성공 로그
Log::info(__('modules.commands.install.success', ['module' => $identifier]));
// 에러 로그
Log::error('모듈 설치 실패', [
'module' => $identifier,
'error' => $e->getMessage(),
]);
```
### 3. 예외 처리
```php
public function handle(): int
{
try {
// 커맨드 로직
$this->info('✅ ' . __('modules.commands.install.success', ['module' => $identifier]));
return Command::SUCCESS;
} catch (\Exception $e) {
$this->error('❌ ' . $e->getMessage());
Log::error('모듈 설치 실패', [
'module' => $identifier,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
```
### 4. 상세 정보 출력
```php
// 모듈 정보 출력
$this->info(' - ' . __('modules.commands.install.version', ['version' => $module->version]));
$this->info(' - ' . __('modules.commands.install.permissions_created', ['count' => $permissionsCount]));
$this->info(' - ' . __('modules.commands.install.menus_created', ['count' => $menusCount]));
```
---
## 커맨드 테스트
### Feature 테스트 작성 필수
모든 커맨드에 대해 Feature 테스트를 작성해야 합니다.
#### 설치 테스트
```php
public function test_can_install_module_via_command(): void
{
// Arrange
$identifier = 'sirsoft-sample';
// Act
$this->artisan('module:install', ['identifier' => $identifier])
->assertSuccessful();
// Assert
$this->assertDatabaseHas('modules', [
'identifier' => $identifier,
'status' => ExtensionStatus::Inactive->value,
]);
}
```
#### 삭제 확인 프롬프트 테스트
```php
public function test_uninstall_requires_confirmation(): void
{
// Arrange
$module = Module::factory()->create(['identifier' => 'test-module']);
// Act & Assert
$this->artisan('module:uninstall', ['identifier' => 'test-module'])
->expectsConfirmation(
__('modules.commands.uninstall.confirm', ['module' => 'test-module']),
'no'
)
->assertSuccessful();
// Module should still exist
$this->assertDatabaseHas('modules', ['identifier' => 'test-module']);
}
```
#### 활성화/비활성화 테스트
```php
public function test_can_activate_module(): void
{
// Arrange
$module = Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Inactive,
]);
// Act
$this->artisan('module:activate', ['identifier' => 'test-module'])
->assertSuccessful();
// Assert
$this->assertDatabaseHas('modules', [
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
}
public function test_can_deactivate_module(): void
{
// Arrange
$module = Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active,
]);
// Act
$this->artisan('module:deactivate', ['identifier' => 'test-module'])
->assertSuccessful();
// Assert
$this->assertDatabaseHas('modules', [
'identifier' => 'test-module',
'status' => ExtensionStatus::Inactive->value,
]);
}
```
---
## 모듈 업데이트 (API + CLI)
모듈 업데이트는 **API 엔드포인트** 또는 **Artisan 커맨드**를 통해 수행됩니다.
### Artisan 커맨드
```bash
# 업데이트 확인
php artisan module:check-updates # 전체
php artisan module:check-updates [identifier] # 단일
# 업데이트 실행
php artisan module:update [identifier]
```
### API 엔드포인트
```text
POST /api/admin/modules/check-updates
POST /api/admin/modules/{moduleName}/update
```
- 감지 우선순위: GitHub > `_bundled` (2단계, `_pending` 미참여)
- 상태 가드 확인 → 백업 → status: Updating → 파일 교체 → 마이그레이션 → 업그레이드 스텝 → 복원
- 에러 발생 시 자동 롤백 (백업에서 복원)
> 상세: [extension-update-system.md](extension-update-system.md)
---
## 관련 문서
- [모듈 개발 기초](module-basics.md) - AbstractModule, 디렉토리 구조
- [모듈 라우트 규칙](module-routing.md) - 라우트 네이밍, 자동 Prefix
- [모듈 레이아웃 시스템](module-layouts.md) - 레이아웃 등록, 오버라이드
- [권한 시스템](permissions.md) - 모듈 Role/Permission 자동 관리
- [확장 업데이트 시스템](extension-update-system.md) - 업데이트 감지/실행 전체 흐름
+336
View File
@@ -0,0 +1,336 @@
# 모듈 다국어 시스템
> **관련 문서**: [index.md](index.md) | [module-basics.md](module-basics.md) | [module-routing.md](module-routing.md)
---
## TL;DR (5초 요약)
```text
1. 백엔드: /lang/{locale}/*.php → __('vendor-module::key')
2. 프론트엔드: /resources/lang/{locale}.json → $t:key
3. JSON에 moduleIdentifier 포함 금지! (자동 병합됨)
4. 지원 언어: ko, en 필수
5. 키 충돌 방지: 모듈별 고유 prefix 사용 권장
```
---
## 목차
- [핵심 원칙](#핵심-원칙)
- [백엔드 다국어](#백엔드-다국어)
- [프론트엔드 다국어](#프론트엔드-다국어)
- [레이아웃 JSON에서 사용](#레이아웃-json에서-사용)
---
## 핵심 원칙
### 다국어 파일 구조
```
중요: 백엔드와 프론트엔드 다국어 파일 경로 구분
✅ 필수: resources/lang/*.json 파일에 moduleIdentifier 없이 작성
```
| 구분 | 파일 경로 | 형식 | 사용처 |
|------|----------|------|--------|
| 백엔드 | `/lang/{locale}/*.php` | PHP 배열 | Laravel `__()` 함수 |
| 프론트엔드 | `/resources/lang/{locale}.json` | JSON | 레이아웃 JSON `$t:` 문법 |
### moduleIdentifier 규칙
```
✅ 프론트엔드 다국어 파일에는 moduleIdentifier 없이 순수 키만 작성
✅ 템플릿 서빙 시 자동으로 moduleIdentifier를 최상위 키로 병합
❌ 내부 JSON 파일에 { "sirsoft-sample": { ... } } 형태로 작성 금지
```
---
## 백엔드 다국어
### 파일 위치
```
modules/sirsoft-sample/
└── src/
└── lang/
├── ko/
│ └── messages.php
└── en/
└── messages.php
```
**중요**: 백엔드 다국어 파일은 반드시 `src/lang/` 디렉토리에 위치해야 합니다. TranslationServiceProvider가 이 경로에서 파일을 자동으로 로드합니다.
### 파일 형식 (PHP 배열)
```php
// src/lang/ko/messages.php
return [
'product_created' => '상품이 생성되었습니다.',
'order_confirmed' => '주문이 확인되었습니다.',
'validation' => [
'name_required' => '상품명은 필수 항목입니다.',
'price_min' => '가격은 0 이상이어야 합니다.',
],
];
```
```php
// lang/en/messages.php
return [
'product_created' => 'Product has been created.',
'order_confirmed' => 'Order has been confirmed.',
'validation' => [
'name_required' => 'Product name is required.',
'price_min' => 'Price must be at least 0.',
],
];
```
### 사용법
Laravel의 `__()` 함수를 사용합니다. **모듈 다국어는 더블 콜론(::) 문법을 사용합니다**:
```php
// 모듈 네임스페이스 사용 (더블 콜론 ::)
__('sirsoft-sample::messages.product_created');
// 결과: '상품이 생성되었습니다.' (ko 로케일)
// 중첩 키
__('sirsoft-sample::messages.validation.name_required');
// 결과: '상품명은 필수 항목입니다.'
// 파라미터 치환
__('sirsoft-sample::messages.greeting', ['name' => '홍길동']);
// messages.php: 'greeting' => ':name님, 환영합니다.'
// 결과: '홍길동님, 환영합니다.'
// ❌ 잘못된 사용 (점 . 사용)
__('sirsoft-sample.messages.product_created'); // 작동하지 않음!
// ✅ 올바른 사용 (더블 콜론 :: 사용)
__('sirsoft-sample::messages.product_created'); // 정상 작동
```
---
## 프론트엔드 다국어
### 파일 위치
```
modules/sirsoft-sample/
└── resources/
└── lang/
├── ko.json
└── en.json
```
### 파일 형식 (JSON)
```json
// resources/lang/ko.json
{
"admin": {
"index": {
"title": "샘플 항목 관리",
"description": "샘플 모듈의 항목을 관리합니다"
},
"create": {
"title": "새 항목 생성",
"submit": "생성하기"
}
},
"messages": {
"save_success": "저장되었습니다.",
"delete_confirm": "정말 삭제하시겠습니까?"
}
}
```
```json
// resources/lang/en.json
{
"admin": {
"index": {
"title": "Sample Item Management",
"description": "Manage sample module items"
},
"create": {
"title": "Create New Item",
"submit": "Create"
}
},
"messages": {
"save_success": "Saved successfully.",
"delete_confirm": "Are you sure you want to delete?"
}
}
```
### moduleIdentifier 자동 병합
템플릿 서빙 시 시스템이 자동으로 moduleIdentifier를 최상위 키로 병합합니다:
```json
// 원본 파일 (resources/lang/ko.json)
{
"admin": {
"index": {
"title": "샘플 항목 관리"
}
}
}
// 서빙 후 (자동 변환)
{
"sirsoft-sample": {
"admin": {
"index": {
"title": "샘플 항목 관리"
}
}
}
}
```
---
## $partial Fragment 시스템
### 개요
프론트엔드 다국어 JSON 파일이 커지면 `$partial` 디렉티브를 사용하여 도메인별로 분리할 수 있습니다.
`ResolvesLanguageFragments` trait이 JSON 로드 시 fragment를 자동으로 병합합니다.
### 디렉토리 구조
```
modules/_bundled/vendor-module/
└── resources/lang/
├── ko.json ← 메인 JSON (fragment 참조 포함)
├── en.json
└── partial/ ← fragment 파일 디렉토리
├── ko/
│ ├── common.json
│ └── admin/
│ ├── locale.json
│ ├── products.json
│ └── orders.json
└── en/
├── common.json
└── admin/
└── ...
```
### $partial 디렉티브 문법
메인 JSON 파일에서 `$partial` 키로 fragment 파일을 참조합니다:
```json
{
"common": {
"$partial": "partial/ko/common.json"
},
"admin": {
"locale": {
"$partial": "partial/ko/admin/locale.json"
},
"products": {
"$partial": "partial/ko/admin/products.json"
}
}
}
```
- `$partial` 값은 **`resources/lang/` 기준 상대 경로**
- `$partial`이 포함된 객체는 fragment 파일의 내용으로 **완전 교체**됨
- fragment 파일 내부에서 다시 `$partial`을 사용한 **중첩 참조 가능** (최대 깊이 제한 적용)
### Fragment 해석 규칙
| 규칙 | 설명 |
| ---- | ---- |
| 최대 깊이 | `MAX_FRAGMENT_DEPTH = 10` (초과 시 해석 중단) |
| 순환 참조 | `fragmentStack`으로 감지, 순환 시 해당 fragment 무시 |
| 파일 미존재 | 해당 `$partial` 객체가 빈 객체로 대체 |
| 재귀 해석 | fragment 내 `$partial`도 재귀적으로 해석 |
### 사용 기준
| 상황 | 권장 |
| ---- | ---- |
| JSON 파일 500줄 이하 | 단일 파일 유지 |
| JSON 파일 500줄 초과 | 도메인별 `$partial` 분리 |
| admin/user 섹션 분리 필요 | `partial/{locale}/admin/`, `partial/{locale}/user/` |
> **참고**: `$partial`은 프론트엔드 JSON(`resources/lang/`)에서만 사용됩니다.
> 백엔드 PHP(`src/lang/`)에서는 사용할 수 없습니다.
---
## 레이아웃 JSON에서 사용
### 기본 문법
레이아웃 JSON에서 `$t:` 접두사를 사용하여 다국어 키를 참조합니다:
```json
{
"id": "page-title",
"type": "basic",
"name": "H1",
"props": {
"text": "$t:sirsoft-sample.admin.index.title"
}
}
```
### 키 구조
```
$t:[moduleIdentifier].[섹션].[하위섹션].[키]
예시:
$t:sirsoft-sample.admin.index.title
$t:sirsoft-sample.messages.save_success
```
### 다양한 사용 예시
```json
{
"id": "page-header",
"type": "composite",
"name": "PageHeader",
"props": {
"title": "$t:sirsoft-sample.admin.index.title",
"description": "$t:sirsoft-sample.admin.index.description"
}
}
```
```json
{
"id": "submit-button",
"type": "basic",
"name": "Button",
"props": {
"text": "$t:sirsoft-sample.admin.create.submit",
"variant": "primary"
}
}
```
---
## 관련 문서
- [모듈 개발 기초](module-basics.md) - AbstractModule, 디렉토리 구조
- [모듈 라우트 규칙](module-routing.md) - 라우트 네이밍, 자동 Prefix
- [모듈 레이아웃 시스템](module-layouts.md) - 레이아웃 등록, 오버라이드
- [데이터 바인딩](../frontend/data-binding.md) - $t: 문법 상세
+667
View File
@@ -0,0 +1,667 @@
# 모듈 레이아웃 시스템
> 이 문서는 그누보드7 모듈의 레이아웃 시스템에 대해 설명합니다. 레이아웃 등록, 오버라이드, 상속 처리를 다룹니다.
---
## TL;DR (5초 요약)
```text
1. 위치: modules/_bundled/vendor-module/resources/layouts/admin/*.json 또는 user/*.json
2. 네이밍: vendor-module.layout-name 형식 (DOT 구분자)
3. admin/ 하위 → Admin 템플릿, user/ 하위 → User 템플릿에 등록
4. 활성화 시 자동 등록, 비활성화 시 자동 삭제
5. 오버라이드: 템플릿 layouts/overrides/vendor-module/ + version_constraint 지원
```
---
## 목차
1. [개요](#개요)
2. [핵심 원칙](#핵심-원칙)
3. [레이아웃 파일 위치](#레이아웃-파일-위치)
4. [레이아웃 네이밍 규칙](#레이아웃-네이밍-규칙)
5. [레이아웃 등록 메커니즘](#레이아웃-등록-메커니즘)
6. [모듈 활성화/비활성화 흐름](#모듈-활성화비활성화-흐름)
7. [레이아웃 오버라이드 시스템](#레이아웃-오버라이드-시스템)
8. [레이아웃 상속 처리](#레이아웃-상속-처리)
9. [DB 저장 규칙](#db-저장-규칙)
10. [캐시 전략](#캐시-전략)
11. [개발 가이드](#모듈-레이아웃-개발-가이드)
12. [문제 해결](#문제-해결)
---
## 개요
모듈은 자체 레이아웃 파일을 제공하여 관리자/사용자 페이지 UI를 구성할 수 있습니다. 모듈 레이아웃은 디렉토리 위치에 따라 활성화된 Admin 또는 User 템플릿에 자동으로 등록되며, 템플릿 오버라이드 시스템을 통해 커스터마이징이 가능합니다.
---
## 핵심 원칙
```text
필수: ModuleManager와 TemplateManager의 일관성 유지
필수: admin/ 하위 레이아웃 → Admin 템플릿에만 등록
필수: user/ 하위 레이아웃 → User 템플릿에만 등록
경고: layouts/ 루트에 직접 배치된 파일은 스킵됨 (admin/ 또는 user/ 하위 필수)
✅ 레이아웃 content는 layoutData 전체를 저장
✅ 모듈 비활성화 시 레이아웃 soft delete
✅ 모듈 재활성화 시 레이아웃 복원
```
---
## 레이아웃 파일 위치
모듈 레이아웃은 `resources/layouts/` 디렉토리에 위치합니다. 디렉토리 위치에 따라 등록 대상 템플릿이 결정됩니다.
```
modules/
└── _bundled/
└── vendor-module/
└── resources/
└── layouts/
├── admin/ ← Admin 템플릿에 등록
│ ├── index.json
│ └── edit.json
└── user/ ← User 템플릿에 등록
├── main.json
└── detail.json
```
> **주의**: `layouts/` 루트에 직접 배치된 파일(예: `layouts/settings.json`)은 등록되지 않고 경고 로그가 출력됩니다. 반드시 `admin/` 또는 `user/` 하위에 배치하세요.
### 등록 대상 템플릿 결정
| 파일 위치 | 등록 대상 | 예시 |
| ----------------------- | ------------------- | ------------------- |
| `layouts/admin/*.json` | 활성 Admin 템플릿 | sirsoft-admin_basic |
| `layouts/user/*.json` | 활성 User 템플릿 | sirsoft-user_theme1 |
| `layouts/*.json` (루트) | 등록 안됨 (스킵) | 경고 로그 출력 |
---
## 레이아웃 네이밍 규칙
### 자동 생성 패턴
```
{module-identifier}.{layout_path}
```
모듈 레이아웃은 DB에 등록될 때 `moduleIdentifier`가 점(`.`) 구분자로 접두사에 추가됩니다.
### 예시
```
파일: modules/_bundled/sirsoft-sample/resources/layouts/admin/index.json
파일 내 layout_name: admin_sample_index
DB 등록명: sirsoft-sample.admin_sample_index
파일: modules/_bundled/sirsoft-sample/resources/layouts/admin/edit.json
파일 내 layout_name: admin_sample_edit
DB 등록명: sirsoft-sample.admin_sample_edit
파일: modules/_bundled/sirsoft-sample/resources/layouts/user/main.json
파일 내 layout_name: user_sample_main
DB 등록명: sirsoft-sample.user_sample_main
```
### 중요 사항
- 레이아웃 파일 내에서는 `layout_name`을 **접두사 없이** 작성합니다
- 시스템이 자동으로 `{moduleIdentifier}.{layout_name}` 형식으로 변환합니다
- 점(`.`) 구분자는 moduleIdentifier와 layoutName의 경계를 명확히 구분합니다
### 파일 내 layout_name 지정 예시
```json
{
"layout_name": "admin_sample_index",
"version": "1.0.0",
"extends": "_admin_base",
"meta": {
"title": "$t:sirsoft-sample.admin.index.title"
},
"slots": {
"content": [...]
}
}
```
이 레이아웃은 DB에 `sirsoft-sample.admin_sample_index`로 등록됩니다.
---
## 레이아웃 등록 메커니즘
### ModuleManager.registerLayoutToTemplate()
```php
protected function registerLayoutToTemplate(
Template $template,
string $layoutName,
array $layoutData,
string $moduleIdentifier
): void
{
// TemplateManager와 동일하게 layoutData 전체 저장
$content = $layoutData;
TemplateLayout::updateOrCreate(
[
'template_id' => $template->id,
'name' => $layoutName,
],
[
'content' => $content, // extends, layout_name 포함
'extends' => $layoutData['extends'] ?? null,
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
]
);
}
```
**중요**: `content`에는 `layoutData` 전체가 저장되므로 `extends`, `layout_name`, `version` 등 모든 필드가 포함됩니다.
---
## 모듈 활성화/비활성화 흐름
### 1. 모듈 활성화 (activateModule)
```php
public function activateModule(string $moduleName): array
{
// 1. 모듈 activate() 실행
$result = $module->activate();
if ($result) {
// 2. 모듈 상태를 Active로 변경
Module::where('identifier', $module->getIdentifier())
->update(['status' => ExtensionStatus::Active->value]);
// 3. soft deleted된 레이아웃 복원 (재활성화 시)
$this->restoreModuleLayouts($module->getIdentifier());
// 4. 레이아웃 등록 (새로운 레이아웃 또는 업데이트)
$layoutsRegistered = $this->registerModuleLayouts($moduleName);
// 5. 캐시 무효화
$this->invalidateLayoutCache($module->getIdentifier());
}
return ['success' => $result, 'layouts_registered' => $layoutsRegistered];
}
```
### 2. 모듈 비활성화 (deactivateModule)
```php
public function deactivateModule(string $moduleName): array
{
// 1. 모듈 deactivate() 실행
$result = $module->deactivate();
if ($result) {
// 2. 모듈 상태를 Inactive로 변경
Module::where('identifier', $module->getIdentifier())
->update(['status' => ExtensionStatus::Inactive->value]);
// 3. 모듈 레이아웃 soft delete
$layoutsDeleted = $this->softDeleteModuleLayouts($module->getIdentifier());
// 4. 캐시 무효화
$this->invalidateLayoutCache($module->getIdentifier());
}
return ['success' => $result, 'layouts_deleted' => $layoutsDeleted];
}
```
### 3. 템플릿 활성화 시 레이아웃 등록 (activateTemplate)
새 템플릿이 활성화되면 `TemplateManager::activateTemplate()`이 기존 활성 모듈/플러그인의 레이아웃을 새 템플릿에 자동으로 등록합니다.
```php
// TemplateManager::activateTemplate() 내부 (트랜잭션)
DB::transaction(function () use ($templateName, $template, $templateRecord) {
// 1. 같은 타입의 기존 활성 템플릿 비활성화
$this->deactivateTemplatesByType($template['type']);
// 2. 상태 업데이트
$this->templateRepository->updateByIdentifier($templateName, [...]);
// 3. 레이아웃 확장(layout_extensions) 등록
$this->layoutExtensionService->registerAllActiveExtensionsToTemplate($templateRecord->id);
// 4. 활성 모듈/플러그인의 레이아웃을 새 템플릿에 등록
app(ModuleManager::class)->registerLayoutsForAllActiveModules();
app(PluginManager::class)->registerLayoutsForAllActivePlugins();
// 5. 캐시 워밍
$this->warmTemplateCache($templateName);
});
```
**중요**: `registerModuleLayouts()`는 `updateOrCreate` 패턴을 사용하므로 중복 호출에 안전합니다.
### 4. Soft Delete/Restore 이유
| 작업 | 설명 |
|------|------|
| **Soft Delete** | 모듈 재활성화 시 레이아웃 복원을 위해 |
| **Hard Delete** | 모듈 제거(uninstall) 시에만 사용 |
**장점**: 모듈 설정 및 오버라이드 데이터 보존
---
## 레이아웃 오버라이드 시스템
### 우선순위 (LayoutResolverService)
```
1. 템플릿 오버라이드 (source_type = 'template')
2. 모듈 기본 레이아웃 (source_type = 'module')
```
### 오버라이드 생성 예시
```php
// 템플릿에서 모듈 레이아웃 오버라이드
TemplateLayout::create([
'template_id' => $templateId,
'name' => 'sirsoft-sample.admin_sample_index', // 모듈 레이아웃명과 동일
'content' => $customizedLayoutData, // 커스터마이징된 데이터
'extends' => '_admin_base',
'source_type' => LayoutSourceType::Template, // 오버라이드 표시
'source_identifier' => 'sirsoft-admin_basic',
'created_by' => Auth::id(),
]);
```
### 오버라이드 해석 로직
```php
// LayoutService.resolveLayout()
if ($this->isModuleLayoutName($layoutName)) {
// LayoutResolverService를 통해 우선순위 적용
$resolved = $this->layoutResolverService->resolve($layoutName, $templateId);
// 오버라이드가 있으면 오버라이드 반환, 없으면 모듈 기본 반환
return $resolved;
}
```
### 오버라이드 버전 호환성 (version_constraint)
템플릿에서 모듈/플러그인의 레이아웃을 오버라이드할 때, 대상 모듈/플러그인의 버전이 변경되면 오버라이드가 호환되지 않을 수 있습니다. `version_constraint` 필드를 사용하여 오버라이드가 적용될 버전 범위를 지정할 수 있습니다.
#### 사용 목적
- 모듈/플러그인 메이저 버전 변경 시 오버라이드 호환성 문제 방지
- 비호환 오버라이드 자동 스킵 및 관리자 경고 표시
- 템플릿 개발자가 지원하는 버전 범위 명시
#### JSON 스키마
```json
{
"layout_name": "admin_sample_index",
"version_constraint": "^1.0",
"injections": [...]
}
```
#### 지원 문법 (Composer Semver)
| 문법 | 의미 | 예시 |
| ---- | ---- | ---- |
| `^1.0` | 1.0.0 이상, 2.0.0 미만 | 1.0.0, 1.5.0, 1.9.9 ✅ / 2.0.0 ❌ |
| `~1.5` | 1.5.0 이상, 2.0.0 미만 | 1.5.0, 1.9.0 ✅ / 2.0.0 ❌ |
| `~1.5.0` | 1.5.0 이상, 1.6.0 미만 | 1.5.0, 1.5.9 ✅ / 1.6.0 ❌ |
| `>=1.0 <2.0` | 명시적 범위 | 1.0.0, 1.9.9 ✅ / 0.9.0, 2.0.0 ❌ |
| `1.0.0 - 1.9.9` | 하이픈 범위 | 1.0.0 ~ 1.9.9 ✅ |
| `1.0.0 \|\| 2.0.0` | OR 조건 | 1.0.0, 2.0.0 ✅ / 1.5.0 ❌ |
#### 동작 방식
1. **version_constraint 없음**: 항상 오버라이드 적용 (하위 호환성 유지)
2. **버전 제약 만족**: 오버라이드 정상 적용
3. **버전 제약 불만족**: 오버라이드 스킵 + 관리자 경고 표시
4. **대상 버전 정보 없음**: 오버라이드 적용 (경고 로그)
#### 관리자 경고 표시
비호환 오버라이드가 감지되면 레이아웃 상단에 Alert 컴포넌트가 자동 주입됩니다:
```
호환성 경고
오버라이드 "sirsoft-admin_basic"가 모듈 버전과 호환되지 않습니다 (요구: ^1.0, 현재: 2.0.0)
```
#### 사용 예시
```json
{
"target_layout": "sirsoft-board.admin_board_settings",
"version_constraint": "^1.0",
"injections": [
{
"target_id": "notification_section",
"position": "after",
"components": [
{
"id": "custom_notification",
"name": "Card",
"type": "composite",
"props": {
"title": "$t:template.custom_notification.title"
}
}
]
}
]
}
```
위 예시에서 `sirsoft-board` 모듈이 2.0.0으로 업데이트되면:
- 오버라이드가 자동으로 스킵됨
- 관리자에게 호환성 경고 표시
- 템플릿 개발자가 오버라이드를 업데이트할 때까지 기본 레이아웃 사용
#### 구현 위치
- **LayoutResolverService**: `checkOverrideVersionCompatibility()` 메서드 (레이아웃 오버라이드)
- **LayoutExtensionService**: `checkVersionCompatibility()` 메서드 (확장 오버라이드)
- **ModuleManager**: `getModuleVersion()` 헬퍼
- **PluginManager**: `getPluginVersion()` 헬퍼
#### 레이아웃 오버라이드에서의 version_constraint
템플릿이 모듈 레이아웃을 오버라이드할 때도 `version_constraint`를 사용할 수 있습니다.
오버라이드 JSON 예시:
```json
{
"layout_name": "admin_sample_index",
"version_constraint": "^1.0",
"extends": "_admin_base",
"slots": {
"content": [...]
}
}
```
동작:
1. `version_constraint` 없음 → 항상 오버라이드 적용
2. 버전 호환 → 오버라이드 적용
3. 버전 비호환 → 오버라이드 스킵, 모듈 기본 레이아웃으로 폴백 + `Log::warning`
---
## 레이아웃 상속 처리
### extends 필드 사용
```json
{
"layout_name": "admin_sample_index",
"extends": "_admin_base",
"slots": {
"content": [...]
}
}
```
### 병합 로직 (LayoutService.mergeLayouts)
```php
// content에 extends가 있어야 병합 수행
if (isset($layoutData['extends'])) {
$parentLayoutName = $layoutData['extends'];
$parentLayout = $this->loadAndMergeLayout($templateId, $parentLayoutName);
$mergedLayout = $this->mergeLayouts($parentLayout, $layoutData);
} else {
$mergedLayout = $layoutData;
}
```
### 병합 결과
```php
$result = [
'version' => $childLayout['version'] ?? $parentLayout['version'] ?? '1.0.0',
'layout_name' => $childLayout['layout_name'] ?? $parentLayout['layout_name'] ?? '',
'meta' => $mergedMeta,
'data_sources' => $mergedDataSources,
'components' => $mergedComponents,
];
```
---
## DB 저장 규칙
### 템플릿 레이아웃과 일관성 유지
| 구분 | TemplateManager | ModuleManager |
|------|----------------|---------------|
| content 저장 | `$layoutData` 전체 | `$layoutData` 전체 |
| extends 포함 | ✅ Yes | ✅ Yes |
| layout_name 포함 | ✅ Yes | ✅ Yes |
| version 포함 | ✅ Yes | ✅ Yes |
### 잘못된 구현 (❌ DON'T)
```php
// 개별 필드만 추출 - 병합 실패 원인
$content = [];
if (isset($layoutData['slots'])) {
$content['slots'] = $layoutData['slots'];
}
if (isset($layoutData['meta'])) {
$content['meta'] = $layoutData['meta'];
}
// extends, layout_name 누락!
```
### 올바른 구현 (✅ DO)
```php
// layoutData 전체 저장 - TemplateManager와 일관성
$content = $layoutData;
```
---
## 캐시 전략
### 무효화 시점
1. 모듈 활성화 후
2. 모듈 비활성화 후
3. 레이아웃 파일 변경 시
### 무효화 메서드
```php
protected function invalidateLayoutCache(string $moduleIdentifier): void
{
// 1. 태그 기반 캐시 삭제
if (method_exists(Cache::getStore(), 'tags')) {
Cache::tags(['layouts', $moduleIdentifier])->flush();
}
// 2. 개별 레이아웃 캐시 삭제
$moduleLayouts = TemplateLayout::where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->get();
foreach ($moduleLayouts as $layout) {
$cacheKey = "layout.{$layout->template_id}.{$layout->name}";
Cache::forget($cacheKey);
}
}
```
### 캐시 무효화 원칙
```text
중요: 모듈/플러그인 활성화/비활성화 시 관련 캐시 자동 무효화 필수
✅ 필수: Manager 레벨에서 캐시 무효화 구현 (Service 아님)
✅ 권장: 공통 캐시 무효화 로직은 트레이트로 분리
```
---
## 모듈 레이아웃 개발 가이드
### 1. 레이아웃 파일 생성
```bash
# 디렉토리 생성
mkdir -p modules/_bundled/sirsoft-sample/resources/layouts/admin
# 레이아웃 파일 생성
touch modules/_bundled/sirsoft-sample/resources/layouts/admin/index.json
```
### 2. 레이아웃 JSON 작성
```json
{
"layout_name": "admin_sample_index",
"version": "1.0.0",
"extends": "_admin_base",
"meta": {
"title": "$t:sirsoft-sample.admin.index.title",
"description": "$t:sirsoft-sample.admin.index.description",
"auth_required": true
},
"slots": {
"content": [
{
"id": "page_header",
"name": "PageHeader",
"type": "composite",
"props": {
"title": "$t:sirsoft-sample.admin.index.title"
}
}
]
},
"data_sources": [
{
"id": "items",
"type": "api",
"method": "GET",
"endpoint": "/api/modules/sirsoft-sample/admin/items",
"auto_fetch": true,
"auth_required": true
}
]
}
```
### 3. 라우트 등록 (routes.json)
```json
{
"routes": [
{
"path": "/admin/sirsoft-sample",
"layout_name": "sirsoft-sample.admin_sample_index",
"permissions": ["sirsoft-sample.admin.view"]
}
]
}
```
### 4. 모듈 활성화
```bash
php artisan module:activate sirsoft-sample
```
---
## 문제 해결
### 레이아웃 병합 안 됨
**원인**: `content`에 `extends` 필드 누락
**해결**:
1. `ModuleManager.registerLayoutToTemplate()`에서 `$layoutData` 전체 저장 확인
2. 모듈 재활성화로 DB 업데이트:
```bash
php artisan module:deactivate sirsoft-sample
php artisan module:activate sirsoft-sample
```
### layout_name 누락 오류
**원인**: `content`에 `layout_name` 필드 누락
**해결**: 위와 동일 (ModuleManager 수정 후 재활성화)
### 오버라이드가 적용 안 됨
**원인**:
1. 레이아웃 이름 불일치
2. `source_type`이 'template'이 아님
3. 캐시 문제
**해결**:
```bash
# 캐시 초기화
php artisan cache:clear
# 레이아웃 이름 확인 (DB 조회)
SELECT name, source_type FROM template_layouts
WHERE name = 'sirsoft-sample.admin_sample_index';
```
### user 레이아웃이 등록되지 않음
**원인**: 레이아웃 파일이 `layouts/user/` 하위에 위치하지 않음
**해결**: `resources/layouts/user/` 디렉토리로 파일 이동
### layouts/ 루트에 배치한 레이아웃이 무시됨
**원인**: `admin/` 또는 `user/` 하위 배치 필수
**해결**: 적절한 하위 디렉토리로 파일 이동. 경고 로그 확인:
```text
"레이아웃 파일이 admin/ 또는 user/ 하위에 위치하지 않아 스킵됩니다: {file}"
```
### 모듈 재활성화 후에도 레이아웃 안 보임
**확인 사항**:
1. 레이아웃 파일 경로가 올바른지 확인
2. JSON 파일 문법 오류 확인
3. `layout_name` 필드가 JSON에 있는지 확인
---
## 관련 문서
- [module-basics.md](module-basics.md) - 모듈 개발 기초
- [module-routing.md](module-routing.md) - 모듈 라우트 규칙
- [module-commands.md](module-commands.md) - 모듈 Artisan 커맨드
- [module-i18n.md](module-i18n.md) - 모듈 다국어
- [template-caching.md](template-caching.md) - 템플릿 캐싱 전략
- [index.md](index.md) - 확장 시스템 인덱스
+343
View File
@@ -0,0 +1,343 @@
# 모듈 라우트 규칙
> 이 문서는 모듈의 백엔드 라우트(API/Web)와 프론트엔드 라우트(routes.json) 작성 규칙을 설명합니다.
---
## TL;DR (5초 요약)
```text
1. URL prefix 자동: /api/admin/[vendor-module]/...
2. name prefix 자동: api.[vendor-module]....
3. 활성화된 모듈만 라우트 등록됨
4. 프론트엔드: routes/admin.json, routes/user.json으로 admin/user 분기
5. 레거시 routes.json은 admin으로 폴백 (경고 로그 출력)
```
---
## 목차
1. [핵심 원칙](#1-핵심-원칙)
2. [라우트 등록 조건](#2-라우트-등록-조건)
3. [자동 적용되는 Prefix](#3-자동-적용되는-prefix)
4. [라우트 파일 작성](#4-라우트-파일-작성)
5. [라우트 네임 컨벤션](#5-라우트-네임-컨벤션)
6. [프론트엔드 라우트 (routes.json)](#6-프론트엔드-라우트-routesjson)
7. [캐시 관리](#7-캐시-관리)
8. [관련 문서](#8-관련-문서)
---
## 1. 핵심 원칙
```
중요: ModuleRouteServiceProvider가 URL prefix와 name prefix를 자동 적용
✅ 필수: 모듈 개발자는 모듈 내부 구조만 정의
✅ 조건: 활성화된 모듈만 라우트가 등록됨
```
---
## 2. 라우트 등록 조건
### 활성화된 모듈만 라우트 등록
- `ModuleRouteServiceProvider`가 DB에서 `status = 'active'`인 모듈만 조회
- 설치되지 않거나 비활성화된 모듈의 라우트는 등록되지 않음
- 모듈 활성화/비활성화 시 라우트가 자동으로 등록/해제됨
### 네임스페이스 변환 규칙
```
디렉토리명 → 네임스페이스
sirsoft-sample → Modules\Sirsoft\Sample
sirsoft-ecommerce → Modules\Sirsoft\Ecommerce
vendor-my-module → Modules\Vendor\My\Module
```
---
## 3. 자동 적용되는 Prefix
### API 라우트
| 항목 | 값 |
|------|-----|
| URL prefix | `api/modules/{module-name}` |
| Name prefix | `api.modules.{module-name}.` |
### 웹 라우트
| 항목 | 값 |
|------|-----|
| URL prefix | `modules/{module-name}` |
| Name prefix | `web.modules.{module-name}.` |
---
## 4. 라우트 파일 작성
### 라우트 파일 위치
```
modules/_bundled/{identifier}/src/routes/
├── api.php # API 라우트
└── web.php # 웹 라우트
```
### ✅ DO: 모듈 내부 구조만 정의
```php
// modules/_bundled/sirsoft-ecommerce/src/routes/api.php
Route::prefix('admin')->middleware(['auth:sanctum', 'admin'])->group(function () {
Route::get('products', [ProductController::class, 'index'])
->name('admin.products.index');
// 최종 Name: api.modules.sirsoft-ecommerce.admin.products.index
// 최종 URL: /api/modules/sirsoft-ecommerce/admin/products
});
```
### ❌ DON'T: prefix 중복 입력
```php
// 잘못된 예시 - prefix가 중복됨
Route::get('products', [ProductController::class, 'index'])
->name('api.modules.sirsoft-ecommerce.admin.products.index');
```
### 라우트 파일 주석 템플릿
```php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| [Module Name] API Routes
|--------------------------------------------------------------------------
|
| 주의: ModuleRouteServiceProvider가 자동으로 prefix를 적용합니다.
| - URL prefix: 'api/modules/{module-name}'
| - Name prefix: 'api.modules.{module-name}.'
|
*/
// 라우트 정의...
```
---
## 5. 라우트 네임 컨벤션
### 구조
```
{type}.modules.{module-name}.{area}.{resource}.{action}
```
### 예시
```
api.modules.sirsoft-ecommerce.admin.products.index
api.modules.sirsoft-ecommerce.admin.products.store
api.modules.sirsoft-ecommerce.admin.orders.show
web.modules.sirsoft-ecommerce.checkout.cart
```
### 구성 요소
| 구성 요소 | 설명 | 적용 방식 |
|-----------|------|-----------|
| `type` | api 또는 web | 자동 적용 |
| `modules` | 모듈임을 나타냄 | 자동 적용 |
| `module-name` | 모듈 식별자 | 자동 적용 |
| `area` | admin, public 등 영역 | 개발자 정의 |
| `resource` | 리소스명 | 개발자 정의 |
| `action` | index, store, show, update, destroy 등 | 개발자 정의 |
---
## 6. 프론트엔드 라우트 (routes.json)
```
중요: 백엔드 라우트(routes/api.php)와 별개로 프론트엔드 라우트도 지원
✅ 위치: modules/{identifier}/resources/routes/admin.json, routes/user.json
✅ 병합: 템플릿 타입(admin/user)에 맞는 모듈 routes만 필터링 병합
✅ 레거시: routes.json은 admin으로 폴백 (경고 로그 출력)
✅ 캐시: 모듈 활성화/비활성화 시 자동 무효화
```
### 디렉토리 구조
```
modules/{identifier}/resources/
├── routes/
│ ├── admin.json ← admin 템플릿 전용 라우트
│ └── user.json ← user 템플릿 전용 라우트 (선택)
└── routes.json ← [레거시] 있으면 admin으로 취급 + 경고 로그
```
### admin/user 분기 규칙
| 라우트 파일 | 서빙 대상 | 설명 |
|------------|----------|------|
| `routes/admin.json` | admin 타입 템플릿 | 관리자 화면 라우트 |
| `routes/user.json` | user 타입 템플릿 | 일반 사용자 화면 라우트 |
| `routes.json` (레거시) | admin 타입 템플릿만 | 하위 호환성, 경고 로그 출력 |
**탐색 우선순위**:
1. `routes/{templateType}.json` 우선 탐색
2. (admin 타입만) `routes.json` 레거시 폴백
3. user 타입은 레거시 `routes.json`을 로드하지 않음
### 기본 구조
```json
{
"version": "1.0.0",
"routes": [
{
"path": "*/admin/sample",
"layout": "admin_sample_index",
"auth_required": true,
"meta": {
"title": "$t:sirsoft-sample.admin.index.title"
}
}
]
}
```
### 병합 방식
**병합 우선순위**:
1. 템플릿 routes 배열이 기본
2. 활성화된 모듈 routes를 **템플릿 타입에 맞게** 필터링하여 병합 (`array_merge`)
3. 플러그인 routes는 **admin 템플릿에만** 포함 (settings 페이지 등 admin 전용)
4. version은 템플릿의 version 사용
**레이아웃 필드 자동 변환**:
- 모듈 routes의 `layout` 필드에 모듈 식별자 접두사 자동 추가
- 예: `"admin_sample_index"` → `"sirsoft-sample.admin_sample_index"`
**최종 API 응답**:
```json
{
"version": "1.0.0",
"routes": [
// 템플릿 routes...
{
"path": "*/admin/sample",
"layout": "sirsoft-sample.admin_sample_index",
"auth_required": true,
"meta": {
"title": "$t:sirsoft-sample.admin.index.title"
}
}
// 다른 모듈 routes (템플릿 타입에 맞는 것만)...
]
}
```
### 모듈 레이아웃과의 연계
**모듈 레이아웃 정의**:
```
modules/{identifier}/resources/layouts/admin/{layout_name}.json
modules/{identifier}/resources/layouts/user/{layout_name}.json
```
**routes에서 레이아웃 참조**:
```json
{
"path": "*/admin/sample",
"layout": "admin_sample_index"
}
```
**레이아웃 조회 우선순위**:
1. 템플릿 오버라이드: `templates/{template}/layouts/overrides/{module}/{layout}.json`
2. 모듈 원본: `modules/{module}/resources/layouts/admin/{layout}.json`
### 다국어 키 사용
**routes.json에서 다국어 참조**:
```json
{
"meta": {
"title": "$t:sirsoft-sample.admin.index.title"
}
}
```
**모듈 다국어 파일**:
```json
// modules/sirsoft-sample/resources/lang/ko.json
{
"admin": {
"index": {
"title": "샘플 모듈 관리"
}
}
}
```
**프론트엔드에서 최종 키**:
- 템플릿 다국어 API가 모듈 다국어 자동 병합
- 최종 키: `sirsoft-sample.admin.index.title`
### 구현 세부사항
**TemplateService**:
```php
// 템플릿 + 모듈 routes 병합 (템플릿 타입에 따라 필터링)
public function getRoutesDataWithModules(string $identifier): array
// 템플릿 타입에 맞는 모듈 routes 로드 (routes/{type}.json 우선, 레거시 폴백)
private function loadActiveModulesRoutesData(string $templateType = 'admin'): array
```
**PublicTemplateController API**:
```
GET /api/public/templates/{identifier}/routes
```
**ClearsTemplateCaches Trait**:
```php
protected function clearAllTemplateRoutesCaches(): void
```
---
## 7. 캐시 관리
### 캐시 키 패턴
```
template.routes.{identifier}
```
### 자동 캐시 무효화
| Manager | 메서드 | 동작 |
|---------|--------|------|
| ModuleManager | `activateModule()` | routes 캐시 무효화 |
| ModuleManager | `deactivateModule()` | routes 캐시 무효화 |
| PluginManager | `activatePlugin()` | routes 캐시 무효화 |
| PluginManager | `deactivatePlugin()` | routes 캐시 무효화 |
---
## 8. 관련 문서
- [모듈 기초](module-basics.md) - 모듈 구조, AbstractModule
- [모듈 레이아웃](module-layouts.md) - 레이아웃 등록, 오버라이드
- [모듈 다국어](module-i18n.md) - 백엔드/프론트엔드 다국어
- [템플릿 라우트](template-routing.md) - 템플릿 라우트 규칙
- [확장 시스템 개요](index.md) - 전체 인덱스
+549
View File
@@ -0,0 +1,549 @@
# 모듈 환경설정 시스템 개발 가이드
> 이 문서는 모듈에서 환경설정 시스템을 구현하는 방법을 설명합니다.
---
## 목차
1. [개요](#1-개요)
2. [디렉토리 구조](#2-디렉토리-구조)
3. [defaults.json 작성](#3-defaultsjson-작성)
4. [SettingsService 구현](#4-settingsservice-구현)
5. [SettingsController 구현](#5-settingscontroller-구현)
6. [API 라우트 설정](#6-api-라우트-설정)
7. [레이아웃 연동](#7-레이아웃-연동)
8. [백엔드에서 설정 조회](#8-백엔드에서-설정-조회)
9. [관련 문서](#9-관련-문서)
---
## 1. 개요
### 1.1 핵심 원칙
```
중요: 모듈 환경설정은 모듈의 책임
✅ 코어는 ModuleSettingsService + 헬퍼 함수(module_setting/module_settings)를 제공
✅ 모듈이 ModuleSettingsInterface를 구현하면 코어가 자동 검색하여 위임
✅ ModuleSettingsInterface 미구현 모듈은 코어 기본 구현(단일 setting.json) 사용
✅ 설정 파일은 모듈별 격리된 경로에 저장
```
### 1.2 설정 조회 흐름
```
module_setting('vendor-module', 'key')
→ ModuleSettingsService::get()
→ resolveModuleService() — 모듈별 설정 서비스 자동 검색
→ 1순위: Modules\{Vendor}\{Module}\Contracts\{Module}SettingsServiceInterface (바인딩)
→ 2순위: Modules\{Vendor}\{Module}\Services\{Module}SettingsService (클래스)
→ 모듈 서비스 발견 시: 위임 (getSetting/getAllSettings)
→ 미발견 시: 코어 기본 구현 (defaults.json + setting.json)
```
### 1.3 설계 원칙
- **격리성**: 모듈별로 독립적인 설정 저장 경로
- **일관성**: 코어 환경설정과 동일한 패턴
- **유연성**: 카테고리별 설정 분리 가능
- **보안성**: frontend_schema를 통한 민감정보 제어
---
## 2. 디렉토리 구조
### 2.1 모듈 설정 파일 위치
```
modules/{vendor-module}/
├── config/
│ └── settings/
│ └── defaults.json ← 기본 설정값 정의
├── src/
│ ├── Services/
│ │ └── {Module}SettingsService.php ← 설정 서비스
│ ├── Http/
│ │ └── Controllers/
│ │ └── Admin/
│ │ └── {Module}SettingsController.php ← 설정 API
│ └── routes/
│ └── api.php ← API 라우트
└── resources/
└── layouts/
└── admin/
└── admin_{module}_settings.json ← 설정 UI
```
### 2.2 설정 저장 경로
```
storage/app/modules/{vendor-module}/settings/
├── basic_info.json
├── language_currency.json
└── seo.json
```
---
## 3. defaults.json 작성
### 3.1 기본 구조
```json
{
"_meta": {
"version": "1.0.0",
"description": "모듈 설명",
"categories": ["basic_info", "language_currency", "seo"]
},
"defaults": {
"basic_info": {
"field_name": "default_value"
}
},
"frontend_schema": {
"basic_info": {
"expose": true,
"fields": {
"field_name": { "expose": true }
}
}
}
}
```
### 3.2 _meta 섹션
| 필드 | 타입 | 설명 |
|------|------|------|
| version | string | 설정 스키마 버전 |
| description | string | 모듈 설명 |
| categories | array | 설정 카테고리 목록 |
### 3.3 defaults 섹션
카테고리별 기본값을 정의합니다.
```json
{
"defaults": {
"basic_info": {
"shop_name": "",
"route_path": "shop",
"no_route": false
},
"seo": {
"meta_main_title": "{site_name} - {commerce_name}",
"seo_site_main": true
}
}
}
```
### 3.4 frontend_schema 섹션
프론트엔드에 노출할 필드를 제어합니다.
```json
{
"frontend_schema": {
"basic_info": {
"expose": true,
"fields": {
"shop_name": { "expose": true },
"api_key": { "expose": false, "sensitive": true }
}
},
"payment": {
"expose": false
}
}
}
```
| 속성 | 설명 |
|------|------|
| expose | 프론트엔드 노출 여부 |
| sensitive | 민감 정보 여부 |
---
## 4. SettingsService 구현
### 4.1 ModuleSettingsInterface 구현
```php
<?php
namespace Modules\Vendor\Module\Services;
use App\Contracts\Extension\ModuleSettingsInterface;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
class ModuleSettingsService implements ModuleSettingsInterface
{
private const MODULE_IDENTIFIER = 'vendor-module';
private ?array $defaults = null;
private ?array $settings = null;
public function getSettingsDefaultsPath(): ?string
{
$path = $this->getModulePath().'/config/settings/defaults.json';
return file_exists($path) ? $path : null;
}
public function getSetting(string $key, mixed $default = null): mixed
{
$settings = $this->getAllSettings();
return Arr::get($settings, $key, $default);
}
public function setSetting(string $key, mixed $value): bool
{
$settings = $this->getAllSettings();
Arr::set($settings, $key, $value);
$parts = explode('.', $key);
$category = $parts[0];
return $this->saveCategorySettings($category, $settings[$category] ?? []);
}
public function getAllSettings(): array
{
if ($this->settings !== null) {
return $this->settings;
}
$defaults = $this->getDefaults();
$categories = $defaults['_meta']['categories'] ?? [];
$defaultValues = $defaults['defaults'] ?? [];
$settings = [];
foreach ($categories as $category) {
$categoryDefaults = $defaultValues[$category] ?? [];
$savedSettings = $this->loadCategorySettings($category);
$settings[$category] = array_merge($categoryDefaults, $savedSettings);
}
$this->settings = $settings;
return $settings;
}
public function getSettings(string $category): array
{
$allSettings = $this->getAllSettings();
return $allSettings[$category] ?? [];
}
public function saveSettings(array $settings): bool
{
$success = true;
foreach ($settings as $category => $categorySettings) {
if (str_starts_with($category, '_')) {
continue;
}
if (!$this->saveCategorySettings($category, $categorySettings)) {
$success = false;
}
}
$this->settings = null;
return $success;
}
public function getFrontendSettings(): array
{
$defaults = $this->getDefaults();
$frontendSchema = $defaults['frontend_schema'] ?? [];
$allSettings = $this->getAllSettings();
$frontendSettings = [];
foreach ($frontendSchema as $category => $schema) {
if (!($schema['expose'] ?? false)) {
continue;
}
$categorySettings = $allSettings[$category] ?? [];
$fields = $schema['fields'] ?? [];
if (empty($fields)) {
$frontendSettings[$category] = $categorySettings;
continue;
}
$exposedFields = [];
foreach ($fields as $fieldName => $fieldSchema) {
if ($fieldSchema['expose'] ?? false) {
$exposedFields[$fieldName] = $categorySettings[$fieldName] ?? null;
}
}
if (!empty($exposedFields)) {
$frontendSettings[$category] = $exposedFields;
}
}
return $frontendSettings;
}
private function getModulePath(): string
{
return base_path('modules/'.self::MODULE_IDENTIFIER);
}
private function getStoragePath(): string
{
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings');
}
// 나머지 private 메서드 구현...
}
```
### 4.2 분리 입력 필드 처리
전화번호, 사업자번호 등 분리 입력 필드 처리:
```php
private function processSplitFields(string $category, array $settings): array
{
if ($category !== 'basic_info') {
return $settings;
}
// 사업자등록번호 병합
if (isset($settings['business_number_1'])) {
$parts = [
$settings['business_number_1'] ?? '',
$settings['business_number_2'] ?? '',
$settings['business_number_3'] ?? '',
];
$settings['business_number'] = implode('-', array_filter($parts));
unset(
$settings['business_number_1'],
$settings['business_number_2'],
$settings['business_number_3']
);
}
return $settings;
}
```
---
## 5. SettingsController 구현
```php
<?php
namespace Modules\Vendor\Module\Http\Controllers\Admin;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Vendor\Module\Services\ModuleSettingsService;
class ModuleSettingsController extends AdminBaseController
{
public function __construct(
private ModuleSettingsService $settingsService
) {
parent::__construct();
}
public function index(): JsonResponse
{
$settings = $this->settingsService->getFrontendSettings();
return $this->success('settings.fetch_success', $settings);
}
public function show(string $category): JsonResponse
{
$settings = $this->settingsService->getSettings($category);
return $this->success('settings.fetch_success', [
'category' => $category,
'settings' => $settings,
]);
}
public function store(Request $request): JsonResponse
{
$result = $this->settingsService->saveSettings($request->all());
if ($result) {
$updatedSettings = $this->settingsService->getFrontendSettings();
return $this->success('settings.save_success', $updatedSettings);
}
return $this->error('settings.save_failed');
}
}
```
---
## 6. API 라우트 설정
### 6.1 라우트 파일 위치
```
modules/{vendor-module}/src/routes/api.php
```
### 6.2 라우트 정의
```php
<?php
use Illuminate\Support\Facades\Route;
use Modules\Vendor\Module\Http\Controllers\Admin\ModuleSettingsController;
/*
|--------------------------------------------------------------------------
| Module API Routes
|--------------------------------------------------------------------------
|
| URL prefix: 'api/modules/{module-name}'
| Name prefix: 'api.modules.{module-name}.'
|
*/
Route::prefix('admin')->middleware(['auth:sanctum', 'admin'])->group(function () {
Route::get('settings', [ModuleSettingsController::class, 'index'])
->name('admin.settings.index');
Route::put('settings', [ModuleSettingsController::class, 'store'])
->name('admin.settings.store');
Route::get('settings/{category}', [ModuleSettingsController::class, 'show'])
->name('admin.settings.show');
});
```
### 6.3 최종 API 경로
| Method | 경로 | 설명 |
|--------|------|------|
| GET | `/api/modules/{id}/admin/settings` | 전체 설정 조회 |
| PUT | `/api/modules/{id}/admin/settings` | 설정 저장 |
| GET | `/api/modules/{id}/admin/settings/{category}` | 카테고리별 조회 |
---
## 7. 레이아웃 연동
### 7.1 data_sources 설정
```json
{
"data_sources": [
{
"id": "settings",
"type": "api",
"endpoint": "/api/modules/{module-id}/admin/settings",
"method": "GET",
"auto_fetch": true,
"auth_required": true,
"initLocal": "form",
"refetchOnMount": true
}
],
"state": {
"isSaving": false,
"hasChanges": false,
"form": {}
}
}
```
### 7.2 저장 버튼 액션
```json
{
"handler": "apiCall",
"auth_required": true,
"target": "/api/modules/{module-id}/admin/settings",
"params": {
"method": "PUT",
"body": "{{_local.form}}"
}
}
```
---
## 8. 백엔드에서 설정 조회
### 8.1 헬퍼 함수 사용 (권장)
`module_setting()` / `module_settings()`는 내부적으로 `ModuleSettingsService`를 사용합니다.
모듈별 설정 서비스(`{Module}SettingsService`)가 존재하면 자동으로 위임합니다.
```php
// 단일 설정값 조회 (도트 노테이션 지원)
$shopName = module_setting('vendor-module', 'basic_info.shop_name', '기본값');
// 전체 설정 조회
$allSettings = module_setting('vendor-module');
// 카테고리 전체 조회
$seoSettings = module_settings('vendor-module', 'seo');
// 전체 설정 조회
$allSettings = module_settings('vendor-module');
```
### 8.2 ModuleSettingsService 직접 사용
```php
use App\Services\ModuleSettingsService;
$service = app(ModuleSettingsService::class);
// 단일 설정값 조회
$value = $service->get('vendor-module', 'basic_info.shop_name', '기본값');
// 전체 설정 조회
$allSettings = $service->get('vendor-module');
```
### 8.3 모듈 내부에서 자체 서비스 사용
모듈 내부 Service/Controller에서는 자체 설정 서비스를 직접 주입하여 사용할 수 있습니다.
모듈 전용 메서드(예: `getStockDeductionTiming()`)가 필요한 경우 이 방식을 사용합니다.
```php
// 모듈 내부 — 모듈 전용 메서드 접근이 필요한 경우
use Modules\Vendor\Module\Services\ModuleSettingsService;
public function __construct(
private ModuleSettingsService $settingsService
) {}
// ModuleSettingsInterface 메서드 + 모듈 전용 메서드 모두 사용 가능
$value = $this->settingsService->getSetting('basic_info.shop_name');
$timing = $this->settingsService->getStockDeductionTiming($method);
```
> **판단 기준**: `getSetting()` 단일 호출만 필요하면 `module_setting()` 헬퍼 사용, 모듈 전용 메서드가 필요하면 서비스 직접 주입
---
## 9. 관련 문서
- [모듈 기초](module-basics.md) - 모듈 구조, AbstractModule
- [모듈 라우트](module-routing.md) - API 라우트 규칙
- [모듈 레이아웃](module-layouts.md) - 레이아웃 등록
- [모듈 다국어](module-i18n.md) - 다국어 지원
---
## 체크리스트
모듈 환경설정 구현 시 확인 사항:
- [ ] `config/settings/defaults.json` 생성
- [ ] `ModuleSettingsInterface` 구현 서비스 생성
- [ ] 설정 컨트롤러 생성
- [ ] API 라우트 등록
- [ ] 레이아웃에 `data_sources` 추가
- [ ] 저장 버튼 액션 연결
- [ ] `frontend_schema`로 민감정보 필터링 설정
+816
View File
@@ -0,0 +1,816 @@
# 권한 시스템
> G7의 권한(Permission)과 역할(Role) 시스템
---
## TL;DR (5초 요약)
```text
1. 구조: User → Role → Permission (기능 레벨)
2. 리소스: User → Role → role_menus 피벗 → Menu
3. 네이밍: [module].[entity].[action] (예: users.read)
4. type 필드: admin(관리자용) 또는 user(사용자용), 기본값: admin
5. scope_type: 역할별 접근 스코프 (null=전체, self=본인, role=소유역할)
```
---
## 목차
1. [권한 아키텍처](#권한-아키텍처)
2. [권한 타입 (Permission Type)](#권한-타입-permission-type)
3. [모듈 Role/Permission 자동 관리](#모듈-rolepermission-자동-관리)
4. [Role 정의 규칙](#role-정의-규칙)
5. [Permission에 Role 할당](#permission에-role-할당)
6. [Role 삭제 조건](#role-삭제-조건)
7. [콘솔 커맨드 출력](#콘솔-커맨드-출력)
8. [권한 네이밍](#권한-네이밍)
9. [리소스 레벨 권한](#리소스-레벨-권한)
10. [레이아웃 컴포넌트 권한 필터링](#레이아웃-컴포넌트-권한-필터링)
---
## 권한 아키텍처
G7의 권한 시스템은 두 가지 레벨로 구성됩니다.
### 기능 레벨 권한 (Feature-level)
```text
User → Role → Permission
```
- **User**: 시스템 사용자
- **Role**: 역할 그룹 (여러 Permission을 묶음)
- **Permission**: 개별 권한 (특정 작업 수행 허용)
### 리소스 레벨 권한 (Resource-level)
```text
User → Role → role_menus 피벗 테이블 → Menu
```
- **role_menus**: 메뉴 접근 권한
> **참고**: 첨부파일(Attachment)은 기능 레벨 권한(`core.attachments.*` + `scope_type`)으로 제어합니다. `role_attachments` 독립 시스템은 폐기되었습니다.
---
## 권한 타입 (Permission Type)
권한은 `type` 필드로 사용 컨텍스트를 구분합니다.
### PermissionType Enum
```php
// app/Enums/PermissionType.php
enum PermissionType: string
{
case Admin = 'admin'; // 관리자 화면용 권한
case User = 'user'; // 사용자(프론트엔드) 화면용 권한
}
```
### 타입별 용도
| 타입 | 용도 | 예시 |
|------|------|------|
| `admin` | 관리자 화면에서 사용되는 권한 | 사용자 관리, 설정, 모듈 관리 |
| `user` | 사용자(프론트엔드) 화면에서 사용되는 권한 | 내 주문 조회, 프로필 수정 |
### 관리자 판단 기준
```php
// User::isAdmin() 메서드
// 사용자가 보유한 권한 중 type='admin'인 것이 하나라도 있으면 관리자
public function isAdmin(): bool
{
return $this->roles()
->whereHas('permissions', function ($query) {
$query->where('type', PermissionType::Admin);
})
->exists();
}
```
### 모듈/플러그인에서 권한 타입 지정
```php
// getPermissions() 반환 구조
'permissions' => [
[
'action' => 'read',
'name' => ['ko' => '조회', 'en' => 'Read'],
'description' => ['ko' => '...', 'en' => '...'],
'type' => 'admin', // admin 또는 user (기본값: admin)
'roles' => ['admin', 'manager'],
],
[
'action' => 'view_own',
'name' => ['ko' => '내 정보 조회', 'en' => 'View Own'],
'type' => 'user', // 사용자 화면용 권한
'roles' => ['user'],
],
],
```
### Permission 모델 헬퍼
```php
// 타입 확인 메서드
$permission->isAdminPermission(); // type === 'admin'
$permission->isUserPermission(); // type === 'user'
// 스코프
Permission::adminPermissions()->get(); // admin 타입만
Permission::userPermissions()->get(); // user 타입만
```
---
## 모듈 Role/Permission 자동 관리
```text
중요: 모듈 설치 시 Role과 Permission이 자동으로 생성/연결됨
✅ 필수: getRoles()와 getPermissions()의 roles 필드 사용
```
> **플러그인 권한**: 플러그인도 모듈과 동일한 3레벨 계층 구조(`categories`)를 사용합니다. 상세는 [plugin-development.md](plugin-development.md)의 "플러그인 권한 시스템" 섹션을 참조하세요.
### 동작 방식
#### 모듈 설치 시 (module:install)
1. 마이그레이션 실행
2. `getRoles()`에서 정의한 Role 생성
3. `getPermissions()`에서 정의한 Permission 생성
4. Permission의 `roles` 필드에 지정된 Role에 권한 할당
5. 메뉴 생성
6. 시더 실행
#### 모듈 제거 시 (module:uninstall)
1. Role에서 Permission 분리 (detach)
2. Permission 삭제
3. Role 삭제 (조건: `extension_type`이 NULL(사용자 생성) AND 남은 권한 0개)
4. 메뉴 삭제
5. 마이그레이션 롤백
---
## Role 정의 규칙
### identifier 네이밍
```text
[vendor-module].[rolename]
```
### 예시
```text
sirsoft-ecommerce.manager
sirsoft-ecommerce.viewer
sirsoft-sample.manager
```
### getRoles() 반환 구조
```php
public function getRoles(): array
{
return [
[
'identifier' => 'sirsoft-ecommerce.manager',
'name' => [
'ko' => '이커머스 관리자',
'en' => 'Ecommerce Manager',
],
'description' => [
'ko' => '이커머스 모듈의 관리 권한을 가진 역할',
'en' => 'Role with management permissions for ecommerce module',
],
],
];
}
```
**필수 필드**:
| 필드 | 타입 | 설명 |
| ------------- | ------ | -------------------------------------- |
| `identifier` | string | 고유 식별자 (vendor-module.rolename) |
| `name` | array | 다국어 역할명 |
| `description` | array | 다국어 설명 |
---
## Permission에 Role 할당
### getPermissions() roles 필드
```php
public function getPermissions(): array
{
return [
[
'identifier' => 'sirsoft-ecommerce.products.view',
'name' => ['ko' => '상품 조회', 'en' => 'View Products'],
'description' => ['ko' => '...', 'en' => '...'],
'roles' => ['admin', 'sirsoft-ecommerce.manager'], // Role 지정
],
];
}
```
### 규칙
- `roles` 필드에 지정된 Role에 자동으로 권한 할당
- 기존 Role의 권한은 `syncWithoutDetaching`으로 보존
- 여러 Role에 동일 권한 할당 가능
### syncWithoutDetaching 동작
```php
// 기존 권한은 유지하면서 새 권한만 추가
$role->permissions()->syncWithoutDetaching($permissionIds);
```
- 모듈 A가 `admin` Role에 권한 할당
- 모듈 B도 `admin` Role에 권한 할당
- 모듈 A 제거 시 모듈 B의 권한은 유지됨
---
## Role 삭제 조건
### 안전한 삭제를 위한 조건
1. `extension_type`이 NULL (사용자 생성 Role만 삭제 가능)
2. `extension_type = 'core'` → 삭제 불가 (코어 역할 보호)
3. `extension_type = 'module'` 또는 `'plugin'` → 삭제 불가 (확장 소유 역할 보호, `ExtensionOwnedRoleDeleteException` 발생)
4. 남은 권한 개수 = 0 (다른 모듈의 권한이 없어야 함)
### 조건을 만족하지 않는 경우
- `extension_type`이 설정된 Role은 `ExtensionOwnedRoleDeleteException` 또는 403 응답
- 남은 권한이 있는 경우 삭제되지 않고 로그에 경고 기록
### Extension Ownership 예시
```php
// 코어 Role (extension_type = 'core', extension_identifier = 'core')
'admin' // 최고 관리자 — 삭제 불가
// 모듈 Role (extension_type = 'module', extension_identifier = 'sirsoft-ecommerce')
'sirsoft-ecommerce.manager' // 모듈 소유 — 삭제 불가
// 사용자 생성 Role (extension_type = NULL)
'custom-role' // 사용자 생성 — 삭제 가능
```
---
## 콘솔 커맨드 출력
### 설치 시
```text
✅ 모듈 "sirsoft-sample" 설치 완료
- 벤더: sirsoft
- 버전: 1.0.0
- 1개 역할 생성됨
- 4개 권한 생성됨
- 3개 메뉴 생성됨
```
### 제거 시
```text
모듈 "sirsoft-sample"을(를) 정말 삭제하시겠습니까?
- 1개 역할이 삭제됩니다.
- 4개 권한이 삭제됩니다.
- 3개 메뉴가 삭제됩니다.
```
---
## 권한 네이밍
### 코어 권한
```text
core.[entity].[action]
```
**예시**:
```text
core.templates.layouts.view
core.templates.layouts.create
core.templates.layouts.edit
core.templates.layouts.delete
core.users.view
core.users.manage
```
### 모듈 권한
```text
[vendor-module].[entity].[action]
```
**예시**:
```text
sirsoft-ecommerce.products.view
sirsoft-ecommerce.products.create
sirsoft-ecommerce.products.edit
sirsoft-ecommerce.products.delete
sirsoft-ecommerce.orders.view
sirsoft-ecommerce.orders.manage
```
### 권한 네이밍 규칙 요약
| 구분 | 패턴 | 예시 |
| ------ | ------------------------------- | ------------------------------------ |
| 코어 | `core.[entity].[action]` | `core.users.view` |
| 모듈 | `[vendor-module].[entity].[action]` | `sirsoft-ecommerce.products.create` |
### 일반적인 action 목록
| Action | 설명 |
| -------- | --------------------------------------- |
| `view` | 조회 권한 |
| `create` | 생성 권한 |
| `edit` | 수정 권한 |
| `delete` | 삭제 권한 |
| `manage` | 관리 권한 (view + create + edit + delete) |
---
## 리소스 레벨 권한
G7은 기능 레벨 권한 외에 **리소스 레벨 권한**을 지원합니다. 특정 리소스(메뉴 등)에 대한 세밀한 접근 제어가 가능합니다.
### 적용된 리소스
| 리소스 | 권한 방식 | 설명 |
| ------------ | --------- | ---- |
| Menu | `role_menus` 피벗 테이블 | 역할별 메뉴 접근 제어 |
| Attachment | `core.attachments.*` + `scope_type` | 기능 레벨 권한으로 제어 |
> **참고**: 첨부파일은 `role_attachments` 독립 시스템이 아닌, 기존 `permissions` + `scope_type` 시스템으로 통합되었습니다.
> - `core.attachments.create`: 업로드 권한
> - `core.attachments.update`: 수정/순서변경 권한 (`resource_route_key: 'attachment'`, `owner_key: 'created_by'`)
> - `core.attachments.delete`: 삭제 권한 (`resource_route_key: 'attachment'`, `owner_key: 'created_by'`)
> - 공개 다운로드는 `HookManager::checkHookPermission('core.attachment.download')` 으로 제어
---
## API 응답 권한 메타 (is_owner + abilities)
모든 API 리소스 응답에 `is_owner`와 `abilities` (can_*) 필드가 표준화되어 포함됩니다.
### 응답 형식
```json
{
"id": 1,
"name": "상품명",
"is_owner": true,
"abilities": {
"can_update": true,
"can_delete": false
}
}
```
- `is_owner`: 현재 요청 사용자가 리소스 소유자인지 여부
- `abilities`: `can_*` 키로 통합된 권한 플래그
### 권한 확인 순서 (checkAbility)
```text
1. Admin 역할 → 무조건 true
2. 인증된 사용자 → $user->hasPermission($identifier)
3. 게스트 → PermissionHelper::check($identifier)
```
### 프론트엔드에서 사용
레이아웃 JSON에서 `abilities.can_*` 키로 접근합니다:
```json
{
"if": "{{item.abilities.can_update}}",
"type": "Button",
"props": { "text": "수정" }
}
```
> **상세 구현 규칙**: [api-resources.md](../backend/api-resources.md#권한-메타-표준화-is_owner--abilities) 참조
---
## PermissionHelper — 서비스/컨트롤러에서 권한 체크
`PermissionHelper` 헬퍼 클래스를 사용하여 서비스/컨트롤러 내부에서 권한을 체크합니다.
scope_type 기반 스코프 체크 기능이 내장되어 있습니다.
```php
use App\Helpers\PermissionHelper;
// 기본 권한 체크
PermissionHelper::check('core.users.update');
// 구조화 권한 (OR/AND)
PermissionHelper::checkWithLogic(['or' => ['perm.a', 'perm.b']]);
// scope_type 기반 상세 접근 체크
PermissionHelper::checkScopeAccess($model, 'core.users.update', $user);
// scope_type 기반 목록 필터링 (Repository에서 사용)
PermissionHelper::applyPermissionScope($query, 'core.users.read');
// effective scope 조회
PermissionHelper::getEffectiveScope('core.users.read', $user); // null|'self'|'role'
// 소유자 정보 조회 (캐싱)
PermissionHelper::getOwnerKey('core.users.read'); // 'id'
PermissionHelper::getResourceRouteKey('core.users.read'); // 'user'
```
**메서드 시그니처**:
```php
public static function check(string $ability, ?User $user = null): bool
public static function checkWithLogic(array|object $permissions, ?User $user = null): bool
public static function checkScopeAccess(Model $model, string $permission, ?User $user = null): bool
public static function applyPermissionScope(Builder $query, string $permission, ?User $user = null): void
public static function getEffectiveScope(string $permission, ?User $user = null): ?string
public static function getOwnerKey(string $permission): ?string
public static function getResourceRouteKey(string $permission): ?string
```
### 권한 체크 방식 선택 가이드
| 상황 | 사용 방법 |
|------|----------|
| 라우트 접근 제어 | `permission:` 미들웨어 (scope_type 자동 체크) |
| 서비스 내부 조건부 권한 체크 | `PermissionHelper::check()` 직접 호출 |
| 상세 엔드포인트 스코프 체크 | `PermissionHelper::checkScopeAccess()` |
| 목록 엔드포인트 필터링 | `PermissionHelper::applyPermissionScope()` (Repository에서 호출) |
| API 응답 abilities 플래그 | `HasAbilityCheck` 트레이트 (`abilityMap()`) |
| 리소스 레벨 접근 제어 (메뉴 등) | `role_*` 피벗 테이블 기반 |
| 레이아웃 컴포넌트 필터링 | `permissions` 속성 (서버 사이드 제거) |
### 주의 사항
```text
❌ AuthServiceProvider::checkPermission() 직접 호출 → PermissionHelper::check() 사용
❌ 서비스 내부에서 미들웨어에 의존한 권한 체크 생략 → PermissionHelper로 명시적 체크
❌ except/only/menu 미들웨어 옵션 사용 (제거됨) → scope_type 데이터 기반 시스템 사용
```
---
## scope_type 스코프 시스템
역할별 접근 범위를 `role_permissions` 피벗의 `scope_type` 컬럼으로 제어합니다.
모든 라우트 미들웨어 옵션 (`except:`, `only:`, `menu:`)은 **제거**되었습니다.
### DB 구조
| 테이블 | 컬럼 | 타입 | 용도 |
|--------|------|------|------|
| `permissions` | `resource_route_key` | VARCHAR(50) NULL | 라우트 파라미터명 (예: 'user', 'menu') |
| `permissions` | `owner_key` | VARCHAR(50) NULL | 모델의 소유자 식별 컬럼 (예: 'id', 'created_by') |
| `role_permissions` | `scope_type` | ENUM('self', 'role') NULL | 역할별 접근 스코프 |
### ScopeType Enum
```php
// app/Enums/ScopeType.php
enum ScopeType: string
{
case Self = 'self'; // 본인 리소스만
case Role = 'role'; // 소유 역할 공유 사용자의 리소스
}
// null = 전체 접근 (제한 없음)
```
### scope_type 값 정의
| 값 | 의미 | 목록 필터링 | 상세 접근 체크 |
|---|---|---|---|
| `null` | 전체 접근 | 필터 미적용 | 항상 통과 |
| `'self'` | 본인 리소스만 | `WHERE {owner_key} = {user_id}` | `$model->{owner_key} === $user->id` |
| `'role'` | 내 역할 범위 | `WHERE {owner_key} IN (내 역할 공유 사용자)` | 소유자가 내 역할 공유하는지 체크 |
### union 정책 (복수 역할 보유 시)
- **우선순위**: `null`(전체) > `'role'`(소유역할) > `'self'`(본인)
- 여러 역할 중 하나라도 scope_type=null → 전체 접근
- 전부 non-null이면 가장 넓은 범위 적용 (role > self)
- 예: 역할A(scope=self) + 역할B(scope=role) → role 적용
### 미들웨어 처리 흐름
```text
permission:admin,core.users.read ← 옵션 없음
1. 권한 타입 검증
2. 동적 파라미터 치환
3. 권한 체크 (인증/게스트)
4. scope_type 스코프 체크:
a. Permission 조회 (캐싱) → resource_route_key, owner_key
b. resource_route_key null → 통과 (시스템 리소스)
c. $request->route(resource_route_key) → 모델 resolve
d. 모델 없음 → 통과 (목록 엔드포인트)
e. 사용자의 effective scope 확인 (union 정책)
f. scope=null → 통과
g. scope='self' → $model->{owner_key} === $user->id
h. scope='role' → 소유자가 내 역할 공유하는지 체크
```
### 목록 엔드포인트 필터링 (Repository 패턴)
```php
// 모든 Repository에서 한 줄로 적용
$query = User::query();
PermissionHelper::applyPermissionScope($query, 'core.users.read');
// ... 기존 필터/정렬/페이지네이션
```
### 소유자 식별 전체 매핑
| Permission prefix | resource_route_key | owner_key | 비고 |
|---|---|---|---|
| core.users.* | user | id | self: $user->id === $model->id |
| core.menus.* | menu | created_by | |
| core.attachments.update/delete | attachment | created_by | create는 scope 불필요 |
| core.schedules.* | schedule | created_by | |
| core.activity_logs.* | null | null | 소유자 없음 |
| sirsoft-board.boards.* | board | created_by | |
| sirsoft-board.{slug}.*.posts.* | post | user_id | |
| sirsoft-ecommerce.products.* | product | created_by | |
| sirsoft-ecommerce.orders.* | order | user_id | |
| sirsoft-page.pages.* | page | created_by | |
> resource_route_key/owner_key가 null → scope_type UI 미표시, 설정해도 무시
### getPermissions() 포맷 (모듈)
```php
'categories' => [
[
'identifier' => 'pages',
'resource_route_key' => 'page', // 리소스 라우트 키
'owner_key' => 'created_by', // 소유자 컬럼
'permissions' => [
[
'action' => 'read',
'roles' => ['admin', 'manager'], // 문자열 → scope_type=null
],
[
'action' => 'delete',
'roles' => [
['role' => 'admin', 'scope_type' => null],
['role' => 'manager', 'scope_type' => 'self'],
],
],
],
],
],
```
### 역할 관리 UI
- PermissionTree 컴포넌트에 scope_type 드롭다운 추가
- resource_route_key가 있는 권한 + 체크된 상태에서만 드롭다운 표시
- 선택지: 전체(null), 소유역할('role'), 본인만('self')
- 폼 데이터: `permissions: [{id: 1, scope_type: null}, {id: 2, scope_type: 'self'}]`
---
## 레이아웃 컴포넌트 권한 필터링
레이아웃 JSON의 컴포넌트에 `permissions` 속성을 정의하면, **레이아웃 서빙 API에서 해당 컴포넌트를 제거하여 서빙**합니다. 프론트엔드 `if` 조건부 렌더링과 달리 JSON 구조 자체가 클라이언트에 노출되지 않아 보안이 강화됩니다.
### 동작 원리
```text
파이프라인 위치:
[캐시 조회] → [extends/partial 병합] → [applyExtensions] → [★ filterComponentsByPermissions] → [훅] → [응답]
```
- **Post-cache filtering**: 캐시 이후 사용자별 동적 필터링 (캐시 구조 영향 없음, ~1-2ms 추가)
- **AND 조건**: `permissions` 배열의 모든 권한을 충족해야 컴포넌트 포함
- **Admin 바이패스**: `admin` 역할은 `Gate::before()`에 의해 모든 권한 통과
### 필터링 대상 영역
| 영역 | 설명 |
|------|------|
| `components` | 메인 컴포넌트 트리 (재귀 children 포함) |
| `modals[]` | 모달 자체에 permissions → 모달 항목 전체 제거 |
| `modals[].components` | 모달 내부 컴포넌트 트리 (재귀) |
| `defines` | 재사용 컴포넌트 정의 (재귀) |
| partial 내부 | extends/partial 병합 후 필터링이므로 자동 처리 |
### 필터링 규칙
1. 현재 노드의 `permissions` 배열 확인 (없거나 빈 배열이면 통과)
2. `AuthServiceProvider::checkPermissions($permissions, $user)` 호출 (AND 조건)
3. 권한 없으면 해당 노드 및 하위 children **전체 제거** (하위 평가 생략)
4. 권한 있으면 통과 → children을 재귀적으로 독립 평가
5. 필터링 완료 후 모든 노드에서 `permissions` 속성 제거 (클라이언트 노출 방지)
### 상위-하위 중복 선언
```json
{
"type": "Div",
"permissions": ["core.users.read"],
"children": [
{ "type": "Button", "permissions": ["core.users.delete"], "text": "삭제" }
]
}
```
| 시나리오 | 상위 결과 | 하위 결과 | 최종 |
|---------|---------|---------|------|
| `read` 없음 | 상위 제거 → 전체 제거 | 평가 안 됨 | 둘 다 없음 |
| `read` 있음 + `delete` 없음 | 통과 | 하위만 제거 | Div만 남음 |
| `read` 있음 + `delete` 있음 | 통과 | 통과 | 둘 다 남음 |
→ 각 노드는 자기 permissions만 독립 평가. 별도 병합 정책 없음.
### 확장(Extension)과의 관계
- Extension Point로 주입된 컴포넌트에 `permissions` → 정상 필터링
- Overlay로 교체된 컴포넌트에 `permissions` → 교체된 컴포넌트의 permissions 적용
- 파이프라인 순서: `applyExtensions` → `filterComponentsByPermissions` (확장 적용 후 필터링)
### 레이아웃 최상위 permissions와의 비교
| 항목 | 최상위 `permissions` | 컴포넌트 `permissions` |
|------|---------------------|----------------------|
| 적용 범위 | 레이아웃 전체 | 개별 컴포넌트 단위 |
| 미충족 시 | 403 응답 | 해당 컴포넌트만 제거 |
| 조건 방식 | AND | AND |
| 처리 시점 | 캐시 조회 전 | 캐시 조회 후 (post-cache) |
### 관련 코드
| 파일 | 역할 |
|------|------|
| `app/Services/LayoutService.php` | `filterComponentsByPermissions()` 메서드 |
| `app/Http/Controllers/Api/Public/PublicLayoutController.php` | 서빙 시 필터링 호출 |
| `app/Rules/ValidLayoutStructure.php` | 컴포넌트 `permissions` 검증 |
> **레이아웃 JSON 문법 상세**: [layout-json.md](../frontend/layout-json.md#컴포넌트별-권한-component-permissions) 참조
---
## Model 권한/역할 체크 메서드
User 모델은 권한/역할 체크를 위한 헬퍼 메서드를 제공합니다.
### 메서드 시그니처
```php
// 단일 권한 체크
$user->hasPermission('core.users.read');
$user->hasPermission('core.users.read', PermissionType::Admin);
// 복수 권한 체크
$user->hasPermissions(['perm.a', 'perm.b'], requireAll: true); // AND
$user->hasPermissions(['perm.a', 'perm.b'], requireAll: false); // OR
// 역할 체크
$user->hasRole('admin');
$user->hasRoles(['admin', 'manager'], requireAll: false); // OR
// 관리자 판단 (admin 타입 권한 보유 여부)
$user->isAdmin();
```
### 인스턴스 레벨 캐싱
`getEffectiveScopeForPermission()` 메서드는 동일 요청 내 반복 호출 시 DB 쿼리를 방지하기 위해 인스턴스 레벨 캐싱을 사용합니다:
```php
// User 모델 내부
protected array $effectiveScopeCache = [];
public function getEffectiveScopeForPermission(string $identifier): ?string
{
if (array_key_exists($identifier, $this->effectiveScopeCache)) {
return $this->effectiveScopeCache[$identifier];
}
// ... DB 쿼리 및 union 정책 적용 ...
return $this->effectiveScopeCache[$identifier] = $result;
}
```
---
## Permission 동기화 및 추적
### Role-Permission 동기화 패턴
역할에 권한을 동기화할 때 이전/이후 상태를 추적합니다:
```php
public function syncPermissions(Role $role, array $permissions): void
{
// 동기화 전 권한 식별자 캡처 (Listener diff 계산용)
$previousPermIdentifiers = $role->permissions()->pluck('identifier')->toArray();
// 피벗 데이터에 granted_at, granted_by 자동 설정
$pivotData = [];
foreach ($permissions as $permission) {
$pivotData[$permission['id']] = [
'scope_type' => $permission['scope_type'] ?? null,
'granted_at' => now(),
'granted_by' => Auth::id(),
];
}
$role->permissions()->sync($pivotData);
// 동기화 후 권한 식별자 (Listener에서 diff 계산 가능)
$currentPermIdentifiers = $role->permissions()->pluck('identifier')->toArray();
HookManager::doAction('core.role.after_sync_permissions',
$role, $previousPermIdentifiers, $currentPermIdentifiers);
}
```
### 자기잠금 방지
마지막 admin 역할 보유자가 자신의 admin 역할을 제거하는 것을 방지합니다:
```text
- 관리자가 자기 자신의 역할을 변경하려 하면 → 역할 변경 무시
- 마지막 admin이 admin 역할을 삭제하려 하면 → 거부
```
---
## 비회원(Guest) 권한
### Guest 권한 체크 흐름
```text
비회원 요청 → PermissionMiddleware
→ Guest 역할 조회 (Role::where('identifier', 'guest'))
→ 정적 캐시: self::$guestRoleCache (요청 내 재사용)
→ 권한 매핑 없음 → 기본 허용
→ 권한 매핑 있음 → guest 역할이 해당 권한 보유하는지 확인
```
### 핵심 규칙
| 상황 | 동작 |
| ------ | ------ |
| 권한 미매핑 (permission_hooks 없음) | 모든 사용자(guest 포함) 허용 |
| 권한 매핑 + guest 역할 보유 | 허용 |
| 권한 매핑 + guest 역할 미보유 | 거부 (401/403) |
---
## Role identifier 자동 생성
관리자가 역할 생성 시 `identifier`를 직접 입력하지 않습니다. `RoleService`가 이름에서 자동 생성합니다:
```text
generateIdentifier(name)
↓ 배열인 경우 → 영어 이름 우선 (en → ko → 첫 번째 값)
↓ Str::slug($baseName, '_') → 슬러그 변환 (예: "Content Manager" → "content_manager")
↓ 중복 체크 → 중복 시 _1, _2, ... suffix 자동 추가
↓ 반환: 고유한 identifier
```
**예시**:
| 입력 이름 | 생성 identifier |
| ---------- | ---------- |
| `Content Manager` | `content_manager` |
| `Content Manager` (중복) | `content_manager_1` |
| `['ko' => '편집자', 'en' => 'Editor']` | `editor` |
---
## 관련 문서
- [menus.md](./menus.md) - 메뉴 권한 시스템
- [hooks.md](./hooks.md) - 훅 권한 시스템
- [module-basics.md](./module-basics.md) - 모듈 기본 구조
- [index.md](./index.md) - 확장 시스템 인덱스
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+609
View File
@@ -0,0 +1,609 @@
# 템플릿 시스템 기초
> **위치**: `docs/extension/template-basics.md`
> **관련 문서**: [index.md](./index.md) | [template-routing.md](./template-routing.md) | [template-security.md](./template-security.md)
---
## TL;DR (5초 요약)
```text
1. 타입: Admin (관리자용), User (일반사용자용)
2. 디렉토리: templates/vendor-template (예: sirsoft-admin_basic)
3. 필수: template.json, routes.json, components.json
4. 코어/템플릿 분리: 코어는 엔진, 템플릿은 컴포넌트
5. 버전 히스토리: Admin만 지원, User는 미지원
```
---
## 목차
1. [개요](#개요)
2. [템플릿 타입](#템플릿-타입)
- [Admin 템플릿](#admin-템플릿)
- [User 템플릿](#user-템플릿)
3. [템플릿 타입별 버전 히스토리 규칙](#템플릿-타입별-버전-히스토리-규칙)
4. [템플릿 네이밍 규칙](#템플릿-네이밍-규칙)
5. [템플릿 메타데이터 (template.json)](#템플릿-메타데이터-templatejson)
6. [에러 페이지 설정 (error_config)](#에러-페이지-설정-error_config)
7. [레이아웃 등록 스캔 범위](#레이아웃-등록-스캔-범위)
8. [역호환성 (다국어 필드)](#역호환성-다국어-필드)
---
## 개요
G7의 템플릿 시스템은 JSON 기반 레이아웃 정의를 통해 동적으로 UI를 생성하는 프론트엔드 아키텍처입니다. 코어는 렌더링 엔진만 제공하고, 실제 컴포넌트는 템플릿별로 독립적으로 구현됩니다.
**핵심 원칙**:
- 코어와 템플릿의 완전한 분리
- JSON 기반 레이아웃 정의
- 컴포넌트 재사용성 극대화
- 다국어 및 권한 기반 렌더링
---
## 템플릿 타입
### Admin 템플릿
**용도**: 관리자 페이지 UI 제공
**특징**:
- 레이아웃은 **읽기 전용** (DB 저장)
- 관리자만 접근 가능
- `/admin/*` 경로 전용
- 예: `sirsoft-admin_basic`
### User 템플릿
**용도**: 일반 사용자 페이지 UI 제공
**특징**:
- 레이아웃 **편집 가능** (사용자 커스터마이징)
- 공개 접근 가능
- `/` 루트 경로 전용
- 예: `sirsoft-user_theme1` (추후 구현 예정)
---
## 템플릿 타입별 버전 히스토리 규칙
```
중요: 템플릿 타입에 따라 버전 히스토리 동작이 다름
✅ 필수: Admin과 User 템플릿의 버전 관리 차이 이해
```
### Admin 템플릿 (`type: "admin"`)
**버전 히스토리**: ❌ **사용하지 않음**
- 레이아웃은 읽기 전용 (수정 불가)
- `template_layout_versions` 테이블 미사용
- 레이아웃 변경 시 직접 `template_layouts.content` 덮어쓰기
- 이유: 디자인 변경만 가능, 레이아웃 구조는 템플릿 교체로만 변경
**구현 예시**:
```php
// Admin 템플릿 레이아웃 업데이트
public function updateAdminLayout(int $id, array $data): TemplateLayout
{
$layout = TemplateLayout::findOrFail($id);
// 버전 생성 없이 직접 수정
$layout->update([
'content' => $data['content'],
]);
return $layout;
}
```
### User 템플릿 (`type: "user"`)
**버전 히스토리**: ✅ **자동 관리**
- 레이아웃 편집 가능 (사용자 커스터마이징)
- `template_layout_versions` 테이블 사용
- 레이아웃 수정 시 자동으로 새 버전 생성
- 버전별 저장/복원 기능 제공
**구현 예시**:
```php
// User 템플릿 레이아웃 업데이트 (버전 자동 생성)
public function updateUserLayout(int $id, array $data): TemplateLayout
{
$layout = TemplateLayout::findOrFail($id);
// 현재 버전 번호 조회
$latestVersion = $layout->versions()->max('version') ?? 0;
$newVersion = $latestVersion + 1;
// 새 버전 생성
TemplateLayoutVersion::create([
'layout_id' => $layout->id,
'version' => $newVersion,
'content' => $data['content'],
'created_by' => auth()->id(),
]);
// 레이아웃 content도 업데이트
$layout->update([
'content' => $data['content'],
]);
return $layout;
}
```
**버전 복원**:
```php
// 특정 버전으로 복원
public function restoreVersion(int $layoutId, int $version): TemplateLayout
{
$layout = TemplateLayout::findOrFail($layoutId);
$versionRecord = $layout->getVersion($version);
if (!$versionRecord) {
throw new Exception('버전을 찾을 수 없습니다.');
}
// 복원 시 새 버전으로 저장
$latestVersion = $layout->versions()->max('version') ?? 0;
TemplateLayoutVersion::create([
'layout_id' => $layout->id,
'version' => $latestVersion + 1,
'content' => $versionRecord->content,
'created_by' => auth()->id(),
]);
$layout->update([
'content' => $versionRecord->content,
]);
return $layout;
}
```
### 비교표
| 항목 | Admin 템플릿 | User 템플릿 |
|------|------------|-----------|
| 레이아웃 편집 | ❌ 불가 | ✅ 가능 |
| 버전 히스토리 | ❌ 미사용 | ✅ 자동 생성 |
| `template_layout_versions` | ❌ 미사용 | ✅ 사용 |
| 레이아웃 복원 | ❌ 불가 | ✅ 가능 |
| 변경 방법 | 템플릿 교체 | 직접 편집 |
---
## 템플릿 네이밍 규칙
**형식**: `[vendor-template]` (GitHub 스타일)
- 소문자 사용
- 하이픈(-) 구분
- vendor: 개발자/조직 식별자
- template: 템플릿명
**디렉토리 예시**:
- `/templates/_bundled/sirsoft-admin_basic/` - sirsoft가 개발한 기본 관리자 템플릿
- `/templates/_bundled/johndoe-admin_dark/` - johndoe가 개발한 다크 모드 관리자 템플릿
### 식별자 검증 규칙
모듈/플러그인/템플릿 공통 식별자 검증 규칙은 [extension-manager.md](./extension-manager.md#식별자-검증-규칙-validextensionidentifier)를 참조하세요.
---
## 템플릿 메타데이터 (template.json)
**위치**: `/templates/_bundled/[vendor-template]/template.json`
### 구조
```json
{
"identifier": "sirsoft-admin_basic",
"vendor": "sirsoft",
"name": "Admin Basic",
"version": "1.0.0",
"license": "MIT",
"description": "Basic admin template for Gnuboard7 platform",
"type": "admin",
"locales": ["ko", "en"],
"dependencies": [],
"features": {
"responsive": true,
"darkMode": true,
"rtl": false
},
"assets": {
"css": ["dist/bundle.css"],
"js": ["dist/bundle.js"]
}
}
```
### 필수 필드
| 필드 | 설명 |
|------|------|
| `identifier` | 템플릿 고유 식별자 (vendor-template 형식) |
| `vendor` | 벤더명 |
| `name` | 템플릿 표시명 |
| `version` | 버전 (Semantic Versioning) |
| `license` | 라이선스 유형 (예: `"MIT"`) — API 리소스의 `license` 필드로 노출 |
| `type` | "admin" 또는 "user" |
| `locales` | 지원 언어 배열 (`config('app.supported_locales')`와 매칭) |
---
## 에러 페이지 설정 (error_config)
```
필수: 모든 템플릿은 에러 페이지 설정을 포함해야 함
✅ 규칙: DB에는 layout_name만 저장되므로 경로 없이 이름만 사용
```
### template.json 설정
```json
{
"error_config": {
"layouts": {
"404": "404",
"403": "403",
"500": "500"
}
}
}
```
### 에러 레이아웃 파일 위치
에러 레이아웃은 반드시 `layouts/errors/` 디렉토리에 위치해야 합니다:
```
templates/_bundled/[vendor-template]/
├── template.json # 메타데이터 (이름, 버전, 라이선스 등 SSoT)
├── seo-config.json # SEO 컴포넌트→HTML 매핑 설정 (선택)
├── LICENSE # 라이선스 전문 (MIT) — API 엔드포인트 `GET /api/admin/templates/{identifier}/license`로 제공
├── layouts/
│ ├── dashboard.json # 일반 레이아웃
│ ├── _admin_base.json # 베이스 레이아웃
│ └── errors/ # 에러 레이아웃 전용
│ ├── 404.json
│ ├── 403.json
│ └── 500.json
```
### 에러 레이아웃 구조
에러 레이아웃도 일반 레이아웃과 동일하게 `extends` + `slots` 패턴을 사용합니다:
```json
{
"extends": "_admin_base",
"slots": {
"content": [
{
"type": "composite",
"name": "EmptyState",
"props": {
"icon": "alert-triangle",
"title": "$t:errors.404.title",
"description": "$t:errors.404.description"
}
}
]
}
}
```
### 설치 시 검증
`TemplateManager::installTemplate()` 호출 시 다음 사항이 자동 검증됩니다:
1. `error_config` 섹션 존재 여부
2. 필수 에러 코드(404, 403, 500) 레이아웃 정의 여부
3. 레이아웃 파일 실제 존재 여부 (`layouts/errors/` 디렉토리 내)
---
## 레이아웃 등록 스캔 범위
```
중요: registerLayouts()는 특정 디렉토리만 스캔
✅ 포함: layouts/*.json (루트) + layouts/errors/*.json
❌ 제외: layouts/partials/ 등 기타 하위 디렉토리
```
### 스캔 대상
| 디렉토리 | 스캔 여부 | 용도 |
|----------|----------|------|
| `layouts/*.json` | ✅ 스캔 | 일반 레이아웃 |
| `layouts/errors/*.json` | ✅ 스캔 | 에러 페이지 레이아웃 |
| `layouts/partials/*.json` | ❌ 제외 | extends로 참조되는 부분 레이아웃 |
### 이유
- `partials/` 디렉토리의 파일은 메인 레이아웃에서 `extends`로 참조되어 병합됨
- 직접 라우팅되지 않으므로 DB에 별도 등록 불필요
- 에러 레이아웃은 `ErrorPageHandler`에서 직접 조회하므로 DB 등록 필요
### TemplateManager.php 구현
```php
// 루트 layouts 디렉토리의 JSON 파일만 스캔
$layoutFiles = File::glob("{$layoutsPath}/*.json");
// errors/ 디렉토리만 추가 스캔 (에러 페이지 레이아웃용)
$errorsPath = "{$layoutsPath}/errors";
if (File::exists($errorsPath)) {
$errorLayoutFiles = File::glob("{$errorsPath}/*.json");
$layoutFiles = array_merge($layoutFiles, $errorLayoutFiles);
}
```
### 모듈 레이아웃 자동 등록
모듈 활성화 시 레이아웃은 디렉토리 위치에 따라 해당 타입의 템플릿에 등록됩니다:
- `modules/{module}/resources/layouts/admin/*.json` → Admin 타입 템플릿에 등록
- `modules/{module}/resources/layouts/user/*.json` → User 타입 템플릿에 등록
이 동작은 `ModuleManager::registerModuleLayouts()`에서 처리됩니다.
---
## 역호환성 (다국어 필드)
```
중요: 다국어 필드의 역호환성 지원
✅ 필수: 문자열 → 다국어 배열 자동 변환
```
### 지원 필드
- `name`: 템플릿명
- `description`: 템플릿 설명
### ModuleInterface/PluginInterface와 동일한 패턴
```php
// ✅ 권장: 다국어 배열 반환
public function getName(): array
{
return [
'ko' => '기본 관리자 템플릿',
'en' => 'Basic Admin Template',
];
}
// 역호환: 문자열 반환 (자동 변환됨)
public function getName(): string
{
return 'Basic Admin Template'; // 자동으로 ['ko' => '...', 'en' => '...']로 변환
}
```
### TemplateManager 자동 변환
```php
// app/Extension/TemplateManager.php
/**
* 문자열을 다국어 배열로 자동 변환
*/
protected function convertToMultilingual($value): array
{
// 이미 배열이면 그대로 반환
if (is_array($value)) {
return $value;
}
// 문자열이면 모든 로케일에 동일한 값 설정
if (is_string($value)) {
$locales = config('app.translatable_locales', ['ko', 'en']);
$result = [];
foreach ($locales as $locale) {
$result[$locale] = $value;
}
return $result;
}
// 그 외 타입은 빈 배열 반환
return [];
}
```
### template.json 예시
```json
{
"identifier": "sirsoft-admin_basic",
"vendor": "sirsoft",
// ✅ 권장: 다국어 객체
"name": {
"ko": "기본 관리자 템플릿",
"en": "Basic Admin Template"
},
"description": {
"ko": "그누보드7용 기본 관리자 템플릿",
"en": "Basic admin template for Gnuboard7 platform"
}
// 역호환: 문자열 (자동 변환됨)
// "name": "Basic Admin Template",
// "description": "Basic admin template for Gnuboard7 platform"
}
```
### DB 저장 형식
```php
// templates 테이블
[
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'description' => ['ko' => 'G7용...', 'en' => 'Basic admin template...'],
]
```
### 역호환성 보장 사항
- ✅ 기존 문자열 기반 template.json 정상 작동
- ✅ 문자열 → 다국어 배열 자동 변환
- ✅ 변환된 값은 모든 로케일에 동일하게 적용
- ✅ Model Accessor (`getLocalizedName()`)에서 올바른 폴백 처리
---
## 템플릿 업데이트 레이아웃 충돌 전략
템플릿 버전 업데이트 시, 관리자가 수정한 레이아웃과 새 버전의 레이아웃이 충돌할 수 있습니다.
### 사전 확인
업데이트 전 수정된 레이아웃을 확인할 수 있습니다:
```text
GET /api/admin/templates/{templateName}/check-modified-layouts
```
응답:
```json
{
"has_modified": true,
"modified_layouts": [
{ "id": 1, "name": "dashboard", "updated_at": "2026-02-24T10:00:00Z" }
]
}
```
### 충돌 해결 전략
업데이트 실행 시 `layout_strategy` 파라미터로 전략을 선택합니다:
| 전략 | 동작 |
|------|------|
| `apply_new` | 새 버전의 레이아웃으로 덮어쓰기 (관리자 수정 사항 유실) |
| `keep_current` | 기존 레이아웃 유지 (새 버전 레이아웃 미적용) |
```text
POST /api/admin/templates/{templateName}/update
Body: { "layout_strategy": "apply_new" }
```
> 상세: [extension-update-system.md](./extension-update-system.md)
---
## 번들 디렉토리 작업 규칙
```text
필수: 템플릿 수정/개발은 _bundled 디렉토리에서만 작업 (활성 디렉토리 직접 수정 금지)
필수: _bundled 작업 완료 후 반영/검증은 업데이트 프로세스 사용
```
### 개발 워크플로우
```text
1. templates/_bundled/{identifier}/ 에서 코드 수정
2. template.json 버전 올리기
3. php artisan template:update {identifier} 로 활성 디렉토리에 반영
4. 테스트 실행으로 검증
```
### 왜 활성 디렉토리 직접 수정이 금지되는가?
- 활성 디렉토리는 `.gitignore` 대상 → Git에 변경 기록 불가
- 다음 업데이트 시 `_bundled` 소스로 덮어쓰기 → 직접 수정 사항 유실
- 업데이트 프로세스 미수행 시 레이아웃 갱신/캐시 무효화 누락
### 예외: 초기 개발 (아직 _bundled에 미등록)
```text
✅ 허용: 신규 템플릿 초기 개발 시 활성 디렉토리에서 직접 작업
전환점: _bundled에 최초 반영한 이후부터는 반드시 _bundled에서만 작업
```
> 상세: [extension-update-system.md](./extension-update-system.md) "번들 디렉토리 개발 워크플로우" 참조
---
## 코드 변경 시 버전 변경 필수
```text
필수: 템플릿 코드를 변경한 경우 버전을 올려야 합니다.
버전 변경 없이 _bundled에 반영하면, 이미 설치된 환경에서 업데이트가 감지되지 않습니다.
참고: 템플릿은 모듈/플러그인과 달리 업그레이드 스텝(upgrades/)을 사용하지 않습니다.
```
### 필수 작업
1. **`template.json` 버전 올리기**: `version` 필드를 Semantic Versioning에 따라 증가
2. **`_bundled` 동기화**: `templates/_bundled/{identifier}/` 디렉토리에 변경 사항 반영
### 템플릿 vs 모듈/플러그인 차이
| 항목 | 템플릿 | 모듈/플러그인 |
|------|--------|-------------|
| manifest 버전 올리기 | ✅ 필수 | ✅ 필수 |
| _bundled 동기화 | ✅ 필수 | ✅ 필수 |
| 업그레이드 스텝 (upgrades/) | ❌ 해당 없음 | 조건부 필요 |
| DB 마이그레이션 | ❌ 해당 없음 | 조건부 필요 |
| 레이아웃 충돌 전략 | ✅ `layout_strategy` 파라미터 | ❌ 해당 없음 |
> 상세: [extension-update-system.md](./extension-update-system.md) "개발자 버전 업데이트 가이드" 참조
---
## SEO 설정 (seo-config.json)
**위치**: `templates/_bundled/[vendor-template]/seo-config.json` (선택 파일)
SEO 페이지 생성기가 컴포넌트를 HTML로 변환할 때 사용하는 매핑 설정입니다. 이 파일이 없으면 모든 컴포넌트가 `<div>` fallback으로 렌더링됩니다.
### 주요 섹션
| 섹션 | 설명 |
|------|------|
| `text_props` | 텍스트 추출 우선순위 (예: `["text", "label", "value", "title"]`) |
| `attr_map` | props→HTML 속성 매핑 (예: `{"className": "class", "htmlFor": "for"}`) |
| `allowed_attrs` | 허용 HTML 속성 목록 (목록에 없는 속성은 출력 안됨) |
| `component_map` | 컴포넌트명 → HTML 태그 매핑 (기본 30개 + 커스텀) |
| `render_modes` | 렌더 모드 정의 (iterate/format/raw 타입) |
| `self_closing` | 셀프 클로징 태그 목록 (`["img", "input", "hr", "br"]`) |
| `stylesheets` | SEO 페이지에 포함할 외부 CSS URL |
### Graceful Degradation
- `text_props`/`attr_map`/`allowed_attrs` 미선언 → 엔진 내장 기본값 사용 (범용 HTML/React 매핑)
- `text_props` 빈 배열로 명시 → props에서 텍스트 추출 불가 (`component.text`는 여전히 동작)
- `attr_map` 빈 객체로 명시 → 속성명 변환 없음 (className→class 미적용)
- `allowed_attrs` 빈 배열로 명시 → 모든 속성 출력 차단
- seo-config.json 미존재 → 모든 컴포넌트 `<div>` fallback, 기본 속성 매핑으로 최소한의 HTML 생성
### 검증
`TemplateManager.validateSeoConfig()`가 설치/업데이트 시 자동 검증합니다:
- JSON 파싱, `component_map.*.tag` 필수, `render` → `render_modes` 교차 참조
- 검증 실패 시 설치/업데이트 차단
- 파일 미존재 시 경고만 (설치 허용)
> 상세 스키마: [seo-system.md](../backend/seo-system.md) "템플릿 seo-config.json" 섹션 참조
## 관련 문서
- [index.md](./index.md) - 확장 시스템 인덱스
- [template-routing.md](./template-routing.md) - 템플릿 라우트/언어 파일 규칙
- [template-security.md](./template-security.md) - 템플릿 보안 정책
- [template-caching.md](./template-caching.md) - 템플릿 캐싱 전략
- [template-commands.md](./template-commands.md) - 템플릿 Artisan 커맨드
- [extension-update-system.md](./extension-update-system.md) - 확장 업데이트 시스템
+523
View File
@@ -0,0 +1,523 @@
# 템플릿 캐싱 전략
> **관련 문서**: [template-basics.md](./template-basics.md) | [template-security.md](./template-security.md) | [index.md](./index.md)
---
## 목차
1. [핵심 원칙](#핵심-원칙)
2. [캐싱 계층](#캐싱-계층)
3. [확장 기능 캐시 버전 (Cache Busting)](#확장-기능-캐시-버전-cache-busting)
4. [캐시 무효화 구현](#캐시-무효화-구현)
5. [서비스에서 캐시 무효화 호출](#서비스에서-캐시-무효화-호출)
6. [캐싱 모범 사례](#캐싱-모범-사례)
7. [성능 벤치마크](#성능-벤치마크)
---
## 핵심 원칙
```
중요: 다층 캐싱으로 성능 최적화
✅ 필수: 캐시 무효화 규칙 준수
```
템플릿 시스템은 여러 계층의 캐싱을 통해 성능을 최적화합니다. 각 캐시는 적절한 TTL(Time To Live)을 가지며, 데이터 변경 시 정확한 무효화가 필수입니다.
---
## 캐싱 계층
### 1. 활성 템플릿 캐시
```php
// 키: templates.active.{type}
// TTL: 3600초 (1시간)
// 값: Template 모델 객체
Cache::remember("templates.active.admin", 3600, function () {
return Template::where('type', 'admin')
->where('is_active', true)
->first();
});
```
**무효화 시점**:
- 템플릿 활성화/비활성화 시
- 템플릿 삭제 시
---
### 2. 레이아웃 JSON 캐시
```php
// 키: template.layout.{layout_name}.{locale}
// TTL: 1800초 (30분)
// 값: 병합된 레이아웃 JSON 배열
Cache::remember("template.layout.dashboard.ko", 1800, function () use ($layoutName, $locale) {
return $this->layoutService->getLayout($layoutName, $locale);
});
```
**무효화 시점**:
- 레이아웃 생성/수정/삭제 시
- 상위 레이아웃(extends) 변경 시
- 로케일 변경 시
---
### 3. 병합된 레이아웃 캐시
상속 체인 처리 결과를 캐싱합니다.
```php
// 키: template.layout.merged.{layout_name}.{locale}
// TTL: 3600초 (1시간)
// 값: extends/slots 병합 완료된 최종 레이아웃
Cache::remember("template.layout.merged.dashboard.ko", 3600, function () use ($layoutName, $locale) {
return $this->layoutService->mergeLayouts($layoutName, [], 0, $locale);
});
```
**무효화 시점**:
- 레이아웃 JSON 캐시 무효화 시 함께 무효화
- 상속 체인의 어느 레이아웃이든 변경 시
---
### 4. 컴포넌트 레지스트리 캐시
```php
// 키: template.components.{identifier}
// TTL: 무제한 (수동 무효화)
// 값: components.json 파싱 결과
Cache::rememberForever("template.components.sirsoft-admin_basic", function () use ($identifier) {
$componentsPath = base_path("templates/{$identifier}/components.json");
return json_decode(file_get_contents($componentsPath), true);
});
```
**무효화 시점**:
- 템플릿 재설치 시
- components.json 수정 시 (개발 중)
---
## 확장 기능 캐시 버전 (Cache Busting)
### 개요
모듈/플러그인/템플릿 활성화/비활성화 시 프론트엔드가 최신 데이터를 즉시 반영하도록 버전 기반 캐시 버스팅을 구현합니다.
```
문제 상황: 브라우저 HTTP 캐시로 인해 모듈 활성화 후 새로고침(Ctrl+F5) 전까지
다국어/라우트 데이터가 반영되지 않음
✅ 해결책: 캐시 버전(타임스탬프) 기반 쿼리 파라미터로 캐시 무효화
```
### 백엔드 구현
#### ClearsTemplateCaches Trait
모듈/플러그인/템플릿 매니저에서 사용하는 공통 trait입니다.
```php
<?php
namespace App\Extension\Traits;
use Illuminate\Support\Facades\Cache;
trait ClearsTemplateCaches
{
/**
* 확장 기능 캐시 버전을 증가시킵니다.
*
* 모듈/플러그인 활성화/비활성화 시 호출되어
* 프론트엔드가 새로운 캐시 버전으로 API를 요청하도록 합니다.
*/
protected function incrementExtensionCacheVersion(): void
{
Cache::put('extension_cache_version', time());
}
/**
* 현재 확장 기능 캐시 버전을 반환합니다.
*
* @return int 캐시 버전 (타임스탬프) 또는 0 (미설정 시)
*/
public static function getExtensionCacheVersion(): int
{
return (int) Cache::get('extension_cache_version', 0);
}
/**
* 모든 활성 템플릿의 언어 캐시를 무효화합니다.
*/
protected function clearAllTemplateLanguageCaches(): void
{
$locales = config('app.supported_locales', ['ko', 'en']);
$templates = Template::where('status', ExtensionStatus::Active->value)->get();
foreach ($templates as $template) {
foreach ($locales as $locale) {
Cache::forget("template.language.{$template->identifier}.{$locale}");
}
}
}
/**
* 모든 활성 템플릿의 routes 캐시를 무효화합니다.
*/
protected function clearAllTemplateRoutesCaches(): void
{
$templates = Template::where('status', ExtensionStatus::Active->value)->get();
foreach ($templates as $template) {
Cache::forget("template.routes.{$template->identifier}");
}
}
}
```
#### 캐시 버전 증가 트리거 시점
| 매니저 | 메서드 | 트리거 상황 |
|--------|--------|------------|
| ModuleManager | `activate()` | 모듈 활성화 |
| ModuleManager | `deactivate()` | 모듈 비활성화 |
| ModuleManager | `refreshModuleLayouts()` | 레이아웃 갱신 시 변경 발생 |
| PluginManager | `activate()` | 플러그인 활성화 |
| PluginManager | `deactivate()` | 플러그인 비활성화 |
| TemplateManager | `activate()` | 템플릿 활성화 |
| TemplateManager | `refreshTemplateLayouts()` | 레이아웃 갱신 시 변경 발생 |
### 프론트엔드 구현
#### 캐시 버전 저장 및 관리
```typescript
// LayoutLoader.ts
private cacheVersion: number = 0;
constructor() {
// localStorage에서 캐시 버전 복원
const stored = localStorage.getItem('g7_extension_cache_version');
this.cacheVersion = stored ? parseInt(stored, 10) : 0;
}
setCacheVersion(version: number): void {
const oldVersion = this.cacheVersion;
this.cacheVersion = version;
localStorage.setItem('g7_extension_cache_version', String(version));
// 버전 변경 시 캐시 무효화
if (oldVersion !== 0 && oldVersion !== version) {
this.clearCache();
}
}
```
#### API 요청 시 버전 파라미터 추가
```typescript
// LayoutLoader.ts
async loadLayout(layoutName: string): Promise<LayoutConfig> {
let url = `/api/layout/${layoutName}`;
if (this.cacheVersion > 0) {
url += `?v=${this.cacheVersion}`;
}
// ...
}
// TranslationEngine.ts
async loadTranslations(identifier: string, locale: string): Promise<void> {
let url = `/api/template/${identifier}/language/${locale}`;
const params: string[] = [];
if (this.cacheVersion > 0) {
params.push(`v=${this.cacheVersion}`);
}
if (params.length > 0) {
url += `?${params.join('&')}`;
}
// ...
}
```
#### 앱 초기화 시 캐시 버전 설정
```typescript
// TemplateApp.ts
async init(): Promise<void> {
// 서버에서 캐시 버전 조회
const response = await fetch('/api/extension/cache-version');
const { version } = await response.json();
// 각 엔진에 버전 설정
this.layoutLoader.setCacheVersion(version);
this.translationEngine.setCacheVersion(version);
}
```
### 캐시 버전 API 엔드포인트
```php
// routes/api.php
Route::get('/extension/cache-version', function () {
return response()->json([
'version' => ClearsTemplateCaches::getExtensionCacheVersion(),
]);
});
```
### 동작 흐름
```
1. 사용자가 모듈 활성화 버튼 클릭
2. 백엔드: ModuleManager->activate() 실행
3. 백엔드: incrementExtensionCacheVersion() 호출 → 캐시 버전 = 현재 타임스탬프
4. 백엔드: clearAllTemplateLanguageCaches() 호출 → 서버 캐시 무효화
5. 프론트엔드: 페이지 새로고침 또는 SPA 라우트 이동
6. 프론트엔드: /api/extension/cache-version 조회
7. 프론트엔드: 버전 변경 감지 → localStorage 업데이트 + 내부 캐시 클리어
8. 프론트엔드: API 요청 시 ?v={version} 파라미터 추가
9. 브라우저: 새로운 URL로 인식하여 캐시 우회 → 최신 데이터 수신
```
### 캐시 버전 키 요약
| 저장소 | 키 | 값 | 용도 |
|--------|-----|-----|------|
| Laravel Cache | `extension_cache_version` | 타임스탬프 | 서버 측 버전 관리 |
| localStorage | `g7_extension_cache_version` | 타임스탬프 | 클라이언트 측 버전 유지 |
---
## 캐시 무효화 구현
### TemplateCacheService
```php
<?php
namespace App\Services\Template;
use Illuminate\Support\Facades\Cache;
class TemplateCacheService
{
/**
* 템플릿 활성화 캐시 무효화
*/
public function invalidateActiveTemplate(string $type): void
{
Cache::forget("templates.active.{$type}");
}
/**
* 레이아웃 캐시 무효화
*/
public function invalidateLayout(string $layoutName): void
{
$locales = config('app.supported_locales', ['ko', 'en']);
foreach ($locales as $locale) {
Cache::forget("template.layout.{$layoutName}.{$locale}");
Cache::forget("template.layout.merged.{$layoutName}.{$locale}");
}
}
/**
* 레이아웃 상속 체인 캐시 무효화
*/
public function invalidateLayoutChain(string $layoutName): void
{
// 현재 레이아웃 무효화
$this->invalidateLayout($layoutName);
// 이 레이아웃을 extends하는 모든 자식 레이아웃 무효화
$children = TemplateLayout::where('extends', $layoutName)->get();
foreach ($children as $child) {
$this->invalidateLayoutChain($child->layout_name);
}
}
/**
* 컴포넌트 레지스트리 캐시 무효화
*/
public function invalidateComponentRegistry(string $identifier): void
{
Cache::forget("template.components.{$identifier}");
}
/**
* 템플릿 전체 캐시 무효화
*/
public function invalidateAllTemplateCache(string $identifier): void
{
// 활성 템플릿 캐시 무효화
$template = Template::where('identifier', $identifier)->first();
if ($template) {
$this->invalidateActiveTemplate($template->type);
}
// 모든 레이아웃 캐시 무효화
$layouts = TemplateLayout::where('template_id', $template->id)->get();
foreach ($layouts as $layout) {
$this->invalidateLayoutChain($layout->layout_name);
}
// 컴포넌트 레지스트리 캐시 무효화
$this->invalidateComponentRegistry($identifier);
}
}
```
---
## 서비스에서 캐시 무효화 호출
### LayoutService 예시
```php
<?php
namespace App\Services\Template;
class LayoutService
{
public function __construct(
private TemplateCacheService $cacheService
) {}
/**
* 레이아웃 수정
*/
public function updateLayout(int $id, array $data): TemplateLayout
{
$layout = TemplateLayout::findOrFail($id);
$oldExtends = $layout->extends;
$layout->update($data);
// 캐시 무효화
$this->cacheService->invalidateLayoutChain($layout->layout_name);
// extends 변경 시 이전 부모의 자식들도 무효화
if ($oldExtends && $oldExtends !== $layout->extends) {
$this->cacheService->invalidateLayoutChain($oldExtends);
}
return $layout->fresh();
}
/**
* 템플릿 활성화
*/
public function activateTemplate(string $identifier): Template
{
$template = Template::where('identifier', $identifier)->firstOrFail();
// 동일 타입의 기존 활성 템플릿 비활성화
Template::where('type', $template->type)
->where('is_active', true)
->update(['is_active' => false]);
$template->update(['is_active' => true]);
// 캐시 무효화
$this->cacheService->invalidateActiveTemplate($template->type);
return $template->fresh();
}
}
```
### 레이아웃 편집(관리자 커스터마이징) 시 캐시 무효화
관리자 UI에서 레이아웃을 직접 편집/복원할 때도 캐시 무효화가 필수입니다.
`LayoutService`의 저장(`updateLayoutContent`) 및 버전 복원(`restoreVersion`) 메서드에서:
1. **`clearDependentLayoutsCache()`** 호출 — 해당 레이아웃 + 이를 extends하는 자식 레이아웃의 병합 캐시 + `PublicLayoutController` 서빙 캐시(`layout.{identifier}.{name}.v{version}`)를 재귀적으로 무효화
2. **`extension_cache_version` 증가** (`Cache::put('extension_cache_version', time())`) — CDN/브라우저 HTTP 캐시 busting. `PublicLayoutController`가 `?v={version}` 기반 캐싱을 사용하므로, 버전 변경 시 브라우저가 새 URL로 인식하여 캐시를 우회합니다.
```php
// LayoutService::updateLayoutContent() 내부
$layout = $this->layoutRepository->update($layout->id, $updateData);
// 캐시 무효화 (현재 레이아웃 + 자식 레이아웃 + PublicLayoutController 서빙 캐시)
$this->clearDependentLayoutsCache($templateId, $name);
// 프론트엔드 브라우저 캐시 무효화
Cache::put('extension_cache_version', time());
```
```php
// LayoutService::restoreVersion() 내부
$newVersion = $this->versionRepository->restoreVersion($layout->id, $versionId);
// 동일하게 캐시 무효화
$this->clearDependentLayoutsCache($templateId, $name);
Cache::put('extension_cache_version', time());
```
이 과정이 누락되면 편집/복원 내용이 실제 사이트에 반영되지 않습니다.
> 참고: `clearDependentLayoutsCache()`는 내부적으로 `clearLayoutCache()`를 호출하며, 이 메서드는 병합 캐시 삭제 + `clearPublicServingCache()`(기본 v0 + 현재 extension_cache_version 캐시 삭제) + 모듈 레이아웃인 경우 `LayoutResolverService` 캐시도 무효화합니다.
---
## 캐싱 모범 사례
### DO (권장)
- ✅ 읽기 빈도가 높은 데이터는 캐싱 필수 (활성 템플릿, 레이아웃 JSON)
- ✅ TTL은 데이터 변경 빈도에 따라 조정
- ✅ 상속 체인 무효화는 재귀적으로 처리
- ✅ 로케일별 캐싱으로 다국어 지원
- ✅ 캐시 키에 의미 있는 이름 사용
### DON'T (금지)
- ❌ 캐시 무효화 누락 금지 (데이터 불일치 발생)
- ❌ 과도한 캐싱으로 메모리 낭비 금지
- ❌ TTL 없이 무제한 캐싱 남용 금지 (컴포넌트 레지스트리 제외)
---
## 성능 벤치마크
참고용 성능 비교 데이터입니다.
| 상태 | 응답 시간 | 개선율 |
|------|----------|--------|
| 캐싱 없음 | 120ms | - |
| 캐싱 적용 | 5ms | 95% ↓ |
---
## 캐시 키 요약
| 캐시 타입 | 키 패턴 | TTL |
|----------|---------|-----|
| 활성 템플릿 | `templates.active.{type}` | 3600초 (1시간) |
| 레이아웃 JSON | `template.layout.{name}.{locale}` | 1800초 (30분) |
| 병합된 레이아웃 | `template.layout.merged.{name}.{locale}` | 3600초 (1시간) |
| 컴포넌트 레지스트리 | `template.components.{identifier}` | 무제한 |
---
## 관련 문서
- [템플릿 기초](./template-basics.md) - 템플릿 타입, 메타데이터
- [템플릿 보안](./template-security.md) - API 서빙, 화이트리스트
- [템플릿 커맨드](./template-commands.md) - Artisan 커맨드
- [확장 시스템 인덱스](./index.md) - 전체 문서 목록
+381
View File
@@ -0,0 +1,381 @@
# 템플릿 Artisan 커맨드
> 템플릿 관련 모든 작업은 Artisan 커맨드를 통해 수행합니다.
---
## TL;DR (5초 요약)
```text
1. 목록: php artisan template:list
2. 설치: php artisan template:install [identifier]
3. 활성화: php artisan template:activate [identifier]
4. 비활성화: php artisan template:deactivate [identifier]
5. 빌드: php artisan template:build [identifier]
```
---
## 목차
1. [핵심 원칙](#핵심-원칙)
2. [사용 가능한 커맨드](#사용-가능한-커맨드)
3. [커맨드 구현 규칙](#커맨드-구현-규칙)
4. [커맨드 테스트](#커맨드-테스트)
5. [문제 해결](#문제-해결)
6. [관련 문서](#관련-문서)
---
## 핵심 원칙
```
필수: 템플릿 관련 모든 작업은 Artisan 커맨드로 수행
✅ 규칙: 직접 DB 조작 또는 파일 시스템 변경 금지
```
---
## 사용 가능한 커맨드
### template:list
템플릿 목록을 조회합니다.
```bash
php artisan template:list
```
**기능**:
- 설치된 모든 템플릿 표시
- 활성화 상태, 타입, 버전 정보 포함
---
### template:install
템플릿을 설치합니다.
```bash
php artisan template:install [vendor-template]
```
**기능**:
- `templates` 테이블에 템플릿 등록
- Vite 빌드 실행 (`npm run build`)
- 컴포넌트 레지스트리 캐시 생성
- 다국어 파일 검증
---
### template:activate
템플릿을 활성화합니다.
```bash
php artisan template:activate [vendor-template]
```
**기능**:
- `templates.is_active` 플래그 설정
- 동일 타입의 기존 활성 템플릿 비활성화
- 캐시 무효화 (`templates.active.{type}`)
---
### template:deactivate
템플릿을 비활성화합니다.
```bash
php artisan template:deactivate [vendor-template]
```
**기능**:
- `templates.is_active` 플래그 해제
- 관련 캐시 무효화
---
### template:uninstall
템플릿을 삭제합니다.
```bash
php artisan template:uninstall [vendor-template]
```
**기능**:
- 템플릿 데이터 삭제 (`templates`, `template_layouts`)
- 의존성 있는 템플릿 확인 후 경고
- 캐시 전체 무효화
---
### template:check-updates
템플릿 업데이트를 확인합니다.
```bash
php artisan template:check-updates [identifier?]
```
**인수**:
- `identifier` (선택): 특정 템플릿만 확인
**기능**:
- **전체 확인** (인수 없음): 설치된 모든 템플릿의 업데이트 가용 여부를 테이블로 출력
- 감지 우선순위: GitHub > `_bundled` (2단계, `_pending` 미참여)
- DB에 `update_available`, `latest_version`, `update_source` 갱신
- **단일 확인** (인수 있음): 특정 템플릿의 업데이트 가용 여부 확인
- `checkTemplateUpdate()`는 DB 갱신 안 함 → 커맨드에서 `updateByIdentifier()` 직접 호출
**예시**:
```bash
# 모든 템플릿 업데이트 확인
php artisan template:check-updates
# 특정 템플릿만 확인
php artisan template:check-updates sirsoft-admin_basic
```
---
### template:update
템플릿을 업데이트합니다.
```bash
php artisan template:update [identifier] [--layout-strategy=overwrite] [--force]
```
**인수**:
- `identifier` (필수): 업데이트할 템플릿 식별자
**옵션**:
- `--layout-strategy=overwrite`: 레이아웃 전략 (`overwrite` | `keep`)
- `--force`: 버전 비교 없이 강제 업데이트 (파일 손상, 수동 수정 복원 시 사용)
**수행 작업**:
- 레이아웃 전략 검증 (`overwrite` | `keep` 외 FAILURE)
- 업데이트 가용 여부 확인 (없으면 info + SUCCESS, `--force` 시 무시하고 진행)
- `overwrite` 전략 시 수정된 레이아웃 경고 (`hasModifiedLayouts()`)
- 확인 프롬프트 → 업데이트 실행
- 실패 시 백업 복원 안내
**예시**:
```bash
# 기본 전략(overwrite)으로 업데이트
php artisan template:update sirsoft-admin_basic
# 레이아웃 보존 전략
php artisan template:update sirsoft-admin_basic --layout-strategy=keep
# 강제 재설치
php artisan template:update sirsoft-admin_basic --force
```
---
### template:cache-clear
레이아웃 캐시를 초기화합니다.
```bash
php artisan template:cache-clear
```
**기능**:
- 모든 템플릿 관련 캐시 삭제
- 활성 템플릿 캐시
- 레이아웃 JSON 캐시
- 컴포넌트 레지스트리 캐시
---
### template:build
템플릿의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리).
```bash
php artisan template:build [identifier]
```
> **기본 빌드 경로**: `_bundled` 디렉토리. 빌드 결과물은 빌드 경로 내에만 남음.
> 활성 디렉토리 반영은 `template:update` 커맨드로만 수행.
**옵션**:
- `--all`: 모든 템플릿의 에셋 빌드 (_bundled 기준, --active 시 활성 기준)
- `--watch`: 파일 변경 감시 모드 (자동으로 활성 디렉토리 사용)
- `--production`: 프로덕션 최적화 빌드
- `--active`: 활성 디렉토리에서 빌드 (_bundled 대신)
**예시**:
```bash
# _bundled에서 빌드 (기본값)
php artisan template:build sirsoft-admin_basic
# 모든 _bundled 템플릿 빌드
php artisan template:build --all
# 프로덕션 빌드 (_bundled)
php artisan template:build sirsoft-admin_basic --production
# 파일 감시 모드 (활성 디렉토리에서 자동 실행)
php artisan template:build sirsoft-admin_basic --watch
# 활성 디렉토리에서 빌드
php artisan template:build sirsoft-admin_basic --active
# 빌드 후 활성 디렉토리 반영
php artisan template:update sirsoft-admin_basic
```
**수행 작업**:
- 빌드 경로 결정: _bundled 우선 → 활성 폴백 (--active 시 활성만)
- npm 의존성 설치 (node_modules 없는 경우)
- Vite를 통한 컴포넌트 번들 빌드
- `dist/components.iife.js` 생성
- 빌드 결과 파일 크기 출력
- **extension_cache_version 증가 (프론트엔드 캐시 무효화)**
- 주의: `--watch` 모드에서는 캐시 버전이 증가하지 않음
---
## 커맨드 구현 규칙
### 1. 다국어 메시지 필수
```php
// ✅ DO: 다국어 메시지 사용
$this->info(__('templates.commands.install.success', ['template' => $identifier]));
// ❌ DON'T: 하드코딩 메시지
$this->info('템플릿 설치 성공');
```
### 2. 로그 기록 필수
```php
use Illuminate\Support\Facades\Log;
// 성공 로그
Log::info(__('templates.commands.install.success', ['template' => $identifier]));
// 에러 로그
Log::error('템플릿 설치 실패', [
'template' => $identifier,
'error' => $e->getMessage(),
]);
```
### 3. 예외 처리 패턴
```php
public function handle(): int
{
try {
// 커맨드 로직
$this->info('✅ ' . __('templates.commands.install.success', ['template' => $identifier]));
return Command::SUCCESS;
} catch (\Exception $e) {
$this->error('❌ ' . $e->getMessage());
Log::error('템플릿 설치 실패', [
'template' => $identifier,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
```
### 4. 상세 정보 출력
```php
// 템플릿 정보 출력
$this->info(' - ' . __('templates.commands.install.type', ['type' => __('templates.types.' . $template->type)]));
$this->info(' - ' . __('templates.commands.install.version', ['version' => $template->version]));
$this->info(' - ' . __('templates.commands.install.layouts_created', ['count' => $template->layouts()->count()]));
```
---
## 커맨드 테스트
Feature 테스트 작성이 필수입니다.
```php
public function test_can_install_template_via_command(): void
{
// Arrange
$identifier = 'test-template';
// Act
$this->artisan('template:install', ['identifier' => $identifier])
->assertSuccessful();
// Assert
$this->assertDatabaseHas('templates', [
'identifier' => $identifier,
'is_active' => false,
]);
}
```
---
## 문제 해결
### 컴포넌트가 렌더링되지 않음
**원인**: ComponentRegistry에 미등록
**해결**:
1. `components.json`에 컴포넌트 추가
2. `npm run build` 실행
3. 캐시 초기화: `php artisan template:cache-clear`
---
### 레이아웃 JSON 저장 실패
**원인**: 검증 규칙 위반
**해결**:
1. 에러 메시지 확인 (FormRequest 검증)
2. 엔드포인트 화이트리스트 확인
3. 컴포넌트명 오타 확인
4. JSON 구조 검증 (최대 깊이 10)
---
### Vite 빌드 에러
**원인**: 의존성 누락 또는 TypeScript 오류
**해결**:
```bash
# 의존성 재설치
npm install
# TypeScript 체크
npm run type-check
# 빌드 로그 확인
npm run build -- --debug
```
---
## 관련 문서
- [템플릿 기초](template-basics.md) - 템플릿 타입, 메타데이터
- [템플릿 라우트](template-routing.md) - routes.json, 언어 파일
- [템플릿 보안](template-security.md) - API 서빙, 화이트리스트
- [템플릿 캐싱](template-caching.md) - 캐시 계층, 무효화
- [인덱스로 돌아가기](index.md)
+366
View File
@@ -0,0 +1,366 @@
# 템플릿 라우트/언어 파일 규칙
> **관련 문서**: [index.md](index.md) | [template-basics.md](template-basics.md) | [template-security.md](template-security.md)
---
## 목차
1. [라우트 정의 (routes.json)](#라우트-정의-routesjson)
2. [템플릿 언어 파일 경로 규칙](#템플릿-언어-파일-경로-규칙)
3. [TemplateService 구현](#templateservice-구현)
4. [API Controller 구현](#api-controller-구현)
5. [라우트 정의](#라우트-정의)
6. [프론트엔드에서 사용](#프론트엔드에서-사용)
7. [보안 규칙](#보안-규칙)
8. [에러 처리](#에러-처리)
9. [모범 사례](#모범-사례)
10. [template.json과의 관계](#templatejson과의-관계)
---
## 라우트 정의 (routes.json)
**위치**: `/templates/[vendor-template]/routes.json`
### 구조
```json
{
"routes": [
{
"path": "/admin/dashboard",
"layout_name": "admin_dashboard",
"permissions": ["core.dashboard.view"],
"meta": {
"title": "대시보드",
"icon": "dashboard"
}
},
{
"path": "/admin/users",
"layout_name": "admin_users_list",
"permissions": ["core.users.view"],
"meta": {
"title": "사용자 관리",
"icon": "users"
}
}
]
}
```
### 필드 설명
| 필드 | 설명 |
|------|------|
| `path` | 라우트 경로 (Laravel 라우트와 일치) |
| `layout_name` | `template_layouts` 테이블의 레이아웃명 |
| `permissions` | 필요한 권한 배열 (빈 배열 시 인증만 필요) |
| `meta` | 메타 정보 (제목, 아이콘 등) |
---
## 템플릿 언어 파일 경로 규칙
```
중요: 템플릿 언어 파일은 API를 통해 제공
✅ 필수: 경로 트래버설 방지 및 로케일 검증
```
### 핵심 원칙
| 항목 | 규칙 |
|------|------|
| **파일 위치** | `/templates/{vendor-template}/lang/{locale}.json` |
| **로케일 형식** | ISO 639-1 (2자리 소문자, 예: `ko`, `en`, `ja`) |
| **제공 방식** | API 엔드포인트 (`/api/templates/{identifier}/lang/{locale}`) |
| **검증** | supported_locales 확인, 경로 탈출 방지 |
### 언어 파일 구조
```json
// /templates/sirsoft-admin_basic/lang/ko.json
{
"dashboard": {
"title": "대시보드",
"subtitle": "시스템 개요",
"stats": {
"users": "총 사용자 수",
"orders": "주문 수"
}
},
"templates": {
"list": "템플릿 목록",
"install": "템플릿 설치",
"activate": "활성화"
}
}
```
```json
// /templates/sirsoft-admin_basic/lang/en.json
{
"dashboard": {
"title": "Dashboard",
"subtitle": "System Overview",
"stats": {
"users": "Total Users",
"orders": "Orders"
}
},
"templates": {
"list": "Template List",
"install": "Install Template",
"activate": "Activate"
}
}
```
---
## TemplateService 구현
```php
<?php
namespace App\Services\Template;
use Illuminate\Support\Facades\File;
class TemplateService
{
/**
* 템플릿 언어 파일 경로 반환
*
* @param string $identifier 템플릿 식별자
* @param string $locale 로케일 (ko, en 등)
* @return array{success: bool, filePath?: string, error?: string}
*/
public function getLanguageFilePath(string $identifier, string $locale): array
{
// 1. 템플릿 활성화 여부 확인
if (!$this->isTemplateActive($identifier)) {
return ['success' => false, 'error' => 'Template not active'];
}
// 2. 로케일 형식 검증 (ISO 639-1: 2자리 소문자)
if (!preg_match('/^[a-z]{2}$/', $locale)) {
return ['success' => false, 'error' => 'Invalid locale format'];
}
// 3. supported_locales 확인
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
if (!in_array($locale, $supportedLocales)) {
return ['success' => false, 'error' => 'Locale not supported'];
}
// 4. 파일 경로 생성
$basePath = base_path("templates/{$identifier}/lang");
$filePath = "{$basePath}/{$locale}.json";
// 5. 경로 트래버설 방지
$realPath = realpath($filePath);
$realBasePath = realpath($basePath);
if (!$realPath || !str_starts_with($realPath, $realBasePath)) {
return ['success' => false, 'error' => 'Invalid file path'];
}
// 6. 파일 존재 확인
if (!File::exists($realPath) || !is_file($realPath)) {
return ['success' => false, 'error' => 'Language file not found'];
}
return ['success' => true, 'filePath' => $realPath];
}
/**
* 템플릿 언어 데이터 로드
*
* @param string $identifier 템플릿 식별자
* @param string $locale 로케일
* @return array
*/
public function getLanguageData(string $identifier, string $locale): array
{
$result = $this->getLanguageFilePath($identifier, $locale);
if (!$result['success']) {
return [];
}
$content = File::get($result['filePath']);
return json_decode($content, true) ?? [];
}
}
```
---
## API Controller 구현
```php
<?php
namespace App\Http\Controllers\Api\Public;
use App\Http\Controllers\Api\Base\PublicBaseController;
use App\Services\Template\TemplateService;
use Illuminate\Http\JsonResponse;
class TemplateLanguageController extends PublicBaseController
{
public function __construct(
private TemplateService $templateService
) {}
/**
* 템플릿 언어 파일 제공
*
* @param string $identifier 템플릿 식별자
* @param string $locale 로케일 (ko, en 등)
* @return JsonResponse
*/
public function getLanguageFile(string $identifier, string $locale): JsonResponse
{
$data = $this->templateService->getLanguageData($identifier, $locale);
if (empty($data)) {
return $this->notFound('messages.template.language_file_not_found');
}
return response()->json($data, 200, [
'Content-Type' => 'application/json',
'Cache-Control' => 'public, max-age=3600',
'Access-Control-Allow-Origin' => '*',
]);
}
}
```
---
## 라우트 정의
```php
// routes/api.php
Route::get('/templates/{identifier}/lang/{locale}', [TemplateLanguageController::class, 'getLanguageFile'])
->where('locale', '[a-z]{2}')
->name('api.templates.language');
```
**주요 포인트**:
- `where('locale', '[a-z]{2}')`: ISO 639-1 형식만 허용
- 라우트 레벨에서 잘못된 형식 차단
---
## 프론트엔드에서 사용
### React 컴포넌트
```javascript
// React 컴포넌트에서 언어 파일 로드
const loadLanguageFile = async (identifier, locale) => {
const response = await fetch(`/api/templates/${identifier}/lang/${locale}`);
if (!response.ok) {
console.error('Failed to load language file');
return {};
}
return await response.json();
};
// 사용 예시
const translations = await loadLanguageFile('sirsoft-admin_basic', 'ko');
console.log(translations.dashboard.title); // "대시보드"
```
### Blade 템플릿
```php
<!-- resources/views/app.blade.php -->
<script>
window.TEMPLATE_LANG_URL = "{{ route('api.templates.language', [
'identifier' => $activeTemplate->identifier,
'locale' => app()->getLocale()
]) }}";
</script>
```
---
## 보안 규칙
### 허용 (✅)
- 활성화된 템플릿만 접근 가능
- ISO 639-1 형식 검증 (정규표현식: `/^[a-z]{2}$/`)
- supported_locales 화이트리스트 확인
- 경로 트래버설 방지 (`realpath()`, `str_starts_with()`)
- 파일 확장자 검증 (`.json`만 허용)
- 적절한 캐싱 헤더 (`Cache-Control: max-age=3600`)
### 금지 (❌)
- 비활성 템플릿 언어 파일 접근 금지
- 임의의 파일 경로 접근 금지
- supported_locales 외 로케일 접근 금지
---
## 에러 처리
| 요청 | 응답 | 사유 |
|------|------|------|
| `GET /api/templates/sirsoft-admin_basic/lang/ko-KR` | 404 Not Found | 라우트 패턴 불일치 |
| `GET /api/templates/sirsoft-admin_basic/lang/ja` | 404 Not Found | supported_locales에 없음 |
| `GET /api/templates/inactive-template/lang/ko` | 404 Not Found | 템플릿 미활성화 |
| `GET /api/templates/sirsoft-admin_basic/lang/fr` | 404 Not Found | 파일 존재하지 않음 |
---
## 모범 사례
### 권장 사항 (✅)
- 모든 템플릿은 최소 `ko.json`, `en.json` 필수 제공
- JSON 파일은 UTF-8 인코딩 사용
- 키 구조는 계층적으로 구성 (`dashboard.stats.users`)
- API를 통한 동적 로딩으로 초기 로딩 시간 최적화
- 브라우저 캐싱 활용 (max-age=3600)
### 금지 사항 (❌)
- 언어 파일에 HTML 포함 금지 (XSS 방지)
- 하드코딩된 텍스트 사용 금지 (모든 텍스트는 언어 파일에서)
---
## template.json과의 관계
```json
// template.json
{
"identifier": "sirsoft-admin_basic",
"locales": ["ko", "en"], // 이 배열에 포함된 언어만 제공
// ...
}
```
### 언어 결정 규칙
- `template.json`의 `locales` 배열이 제공 가능한 언어 명세
- `config('app.supported_locales')`와 교집합이 실제 제공 언어
- 예: `template.json`에 `["ko", "en", "ja"]`, `supported_locales`에 `["ko", "en"]`이면 `ko`, `en`만 제공
---
## 관련 문서
- [index.md](index.md) - 확장 시스템 가이드 인덱스
- [template-basics.md](template-basics.md) - 템플릿 기초
- [template-security.md](template-security.md) - 템플릿 보안 정책
- [template-caching.md](template-caching.md) - 템플릿 캐싱 전략
+390
View File
@@ -0,0 +1,390 @@
# 템플릿 보안 정책
> **목적**: 템플릿 시스템의 보안 정책 및 API 서빙 규칙 가이드
---
## 목차
1. [레이아웃 JSON 검증](#1-레이아웃-json-검증)
2. [의존성 검증](#2-의존성-검증)
3. [XSS 방지](#3-xss-방지)
4. [템플릿 API 서빙 규칙](#4-템플릿-api-서빙-규칙)
5. [파일 확장자 화이트리스트](#5-파일-확장자-화이트리스트)
---
## 1. 레이아웃 JSON 검증
### 검증 계층
```
FormRequest (StoreLayoutRequest)
↓
Custom Rule: ValidLayoutStructure
↓
Custom Rule: WhitelistedEndpoint
↓
Custom Rule: NoExternalUrls
↓
Custom Rule: ComponentExists
```
### 검증 항목
| 항목 | 설명 |
|------|------|
| JSON 구조 유효성 | 올바른 JSON 형식인지 검증 |
| 최대 중첩 깊이 | 10단계 제한 |
| 엔드포인트 화이트리스트 | `/api/(admin\|auth\|public)/` 패턴만 허용 |
| 외부 URL 금지 | 외부 도메인 URL 차단 |
| 컴포넌트 존재 여부 | components.json 기준으로 검증 |
---
## 2. 의존성 검증
### 템플릿 설치 시 체크
- 필수 의존성 템플릿 설치 여부
- 순환 의존성 방지
- 버전 호환성 (Semantic Versioning)
### 예시
```json
// template.json
{
"dependencies": {
"sirsoft-component-library": "^1.0.0"
}
}
```
---
## 3. XSS 방지
### 데이터 바인딩
- 모든 `{{data.field}}` 값은 자동 이스케이프
- `dangerouslySetInnerHTML` 사용 금지
- HTML 삽입 시 서버 검증 필수
### Translation
- `$t:key` 값은 다국어 파일에서만 로드
- 사용자 입력 키 금지
---
## 4. 템플릿 API 서빙 규칙
```
중요: 템플릿 에셋은 API를 통해 제공
✅ 필수: 파일 복사 대신 API 엔드포인트 사용
```
### 원칙
- 템플릿 설치 시 빌드된 파일(`/templates/[vendor-template]/dist/`)은 그대로 유지
- `/public/build/templates/` 디렉토리에 파일 복사하지 않음
- API 엔드포인트를 통해 동적으로 템플릿 에셋 제공
- 보안: 활성화된 템플릿의 에셋만 접근 가능
### API 엔드포인트
```php
// routes/api.php
Route::get('/templates/{identifier}/assets/{file}', [TemplateAssetController::class, 'serve'])
->where('file', '.*')
->name('api.templates.assets');
```
### Controller 구현 (TemplateAssetController)
```php
<?php
namespace App\Http\Controllers\Api\Public;
use App\Http\Controllers\Api\Base\PublicBaseController;
use App\Services\Template\TemplateService;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class TemplateAssetController extends PublicBaseController
{
public function __construct(
private TemplateService $templateService
) {}
/**
* 템플릿 에셋 파일 제공
*
* @param string $identifier 템플릿 식별자
* @param string $file 파일 경로 (예: dist/components.js)
* @return BinaryFileResponse|Response
*/
public function serve(string $identifier, string $file): BinaryFileResponse|Response
{
// 1. 템플릿 활성화 여부 확인
if (!$this->templateService->isTemplateActive($identifier)) {
return $this->notFound('messages.template.not_active');
}
// 2. 파일 경로 검증 (보안)
$allowedExtensions = ['js', 'js.map', 'css', 'css.map', 'woff', 'woff2', 'ttf', 'eot', 'svg', 'png', 'jpg', 'jpeg', 'gif'];
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array($extension, $allowedExtensions)) {
return $this->forbidden('messages.template.invalid_file_type');
}
// 3. 실제 파일 경로 생성
$basePath = base_path("templates/{$identifier}");
$filePath = realpath("{$basePath}/{$file}");
// 4. 디렉토리 탈출 방지
if (!$filePath || !str_starts_with($filePath, $basePath)) {
return $this->forbidden('messages.template.invalid_path');
}
// 5. 파일 존재 확인
if (!file_exists($filePath) || !is_file($filePath)) {
return $this->notFound('messages.template.file_not_found');
}
// 6. MIME 타입 설정
$mimeTypes = [
'js' => 'application/javascript',
'css' => 'text/css',
'map' => 'application/json',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'eot' => 'application/vnd.ms-fontobject',
'svg' => 'image/svg+xml',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
];
$mimeType = $mimeTypes[$extension] ?? 'application/octet-stream';
// 7. 캐싱 헤더 추가
return response()->file($filePath, [
'Content-Type' => $mimeType,
'Cache-Control' => 'public, max-age=31536000, immutable',
'Access-Control-Allow-Origin' => '*',
]);
}
}
```
### Service 메서드
```php
<?php
namespace App\Services\Template;
class TemplateService
{
/**
* 템플릿 활성화 여부 확인
*/
public function isTemplateActive(string $identifier): bool
{
return Cache::remember(
"template.active.{$identifier}",
3600,
fn() => Template::where('identifier', $identifier)
->where('is_active', true)
->exists()
);
}
}
```
### Blade 사용 예시
```php
<!-- resources/views/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
<!-- 활성 템플릿 컴포넌트 로드 -->
@if($activeTemplate)
<script src="{{ route('api.templates.assets', [
'identifier' => $activeTemplate->identifier,
'file' => 'dist/components.js'
]) }}" defer></script>
@endif
</head>
<body>
<!-- 앱 컨텐츠 -->
</body>
</html>
```
### 보안 규칙
| 규칙 | 설명 |
|------|------|
| ✅ 활성화된 템플릿만 접근 가능 | 비활성 템플릿 에셋 접근 차단 |
| ✅ 화이트리스트 기반 확장자 검증 | 허용된 확장자만 제공 |
| ✅ 디렉토리 탈출 공격 방지 | `realpath()`, `str_starts_with()` 사용 |
| ✅ MIME 타입 명시적 설정 | Content-Type 헤더 지정 |
| ✅ 적절한 캐싱 헤더 | `Cache-Control`, `immutable` |
| ❌ 비활성 템플릿 에셋 접근 금지 | 활성화 여부 검증 필수 |
| ❌ 임의의 파일 경로 접근 금지 | 경로 검증 필수 |
### 장점
1. **보안 강화**: 활성화된 템플릿만 접근 가능
2. **디스크 공간 절약**: 파일 복사 불필요
3. **동적 제어**: 템플릿 비활성화 시 즉시 접근 차단
4. **캐싱 최적화**: HTTP 캐싱으로 성능 유지
5. **유지보수 용이**: 단일 소스(dist 디렉토리)만 관리
---
## 5. 파일 확장자 화이트리스트
```
중요: 템플릿 에셋 파일 확장자 제한
✅ 필수: 화이트리스트 기반 확장자 검증
```
### 허용 확장자 목록
#### 스크립트 파일
| 확장자 | 설명 |
|--------|------|
| `js` | JavaScript |
| `mjs` | ES Module JavaScript |
| `js.map` | JavaScript 소스맵 |
#### 스타일 파일
| 확장자 | 설명 |
|--------|------|
| `css` | Cascading Style Sheets |
| `css.map` | CSS 소스맵 |
#### 폰트 파일
| 확장자 | 설명 |
|--------|------|
| `woff` | Web Open Font Format |
| `woff2` | Web Open Font Format 2 |
| `ttf` | TrueType Font |
| `otf` | OpenType Font |
| `eot` | Embedded OpenType |
#### 이미지 파일
| 확장자 | 설명 |
|--------|------|
| `png` | Portable Network Graphics |
| `jpg` | JPEG Image |
| `jpeg` | JPEG Image |
| `svg` | Scalable Vector Graphics |
| `webp` | WebP Image |
| `gif` | Graphics Interchange Format |
#### 데이터 파일
| 확장자 | 설명 |
|--------|------|
| `json` | JSON 데이터 (components.json, template.json 등) |
### TemplateService 구현
```php
// app/Services/TemplateService.php
/**
* 허용된 파일 확장자 화이트리스트
*/
private const ALLOWED_EXTENSIONS = [
'js', 'mjs', 'css', 'json',
'png', 'jpg', 'jpeg', 'svg', 'webp', 'gif',
'woff', 'woff2', 'ttf', 'otf', 'eot',
];
/**
* 파일 확장자 검증
*/
private function validateFileExtension(string $filePath): bool
{
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
// .js.map, .css.map 처리
if (str_ends_with($filePath, '.map')) {
$extension = 'map';
}
return in_array($extension, self::ALLOWED_EXTENSIONS);
}
/**
* MIME 타입 매핑
*/
private function getMimeType(string $extension): string
{
$mimeTypes = [
'js' => 'application/javascript',
'mjs' => 'application/javascript',
'css' => 'text/css',
'json' => 'application/json',
'map' => 'application/json',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'svg' => 'image/svg+xml',
'webp' => 'image/webp',
'gif' => 'image/gif',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'otf' => 'font/otf',
'eot' => 'application/vnd.ms-fontobject',
];
return $mimeTypes[$extension] ?? 'application/octet-stream';
}
```
### 보안 규칙
| 규칙 | 설명 |
|------|------|
| ✅ 화이트리스트에 명시된 확장자만 허용 | 목록 외 차단 |
| ✅ 대소문자 구분 없이 검증 | `strtolower()` 사용 |
| ✅ 소스맵 파일 특별 처리 | `.js.map`, `.css.map` |
| 실행 파일 확장자 금지 | `.php`, `.sh`, `.exe` 등 |
| ❌ 서버 설정 파일 금지 | `.htaccess`, `.env` 등 |
| ❌ 화이트리스트 외 모든 확장자 차단 | 기본 거부 정책 |
### 금지 확장자 예시 (절대 추가 금지)
| 카테고리 | 확장자 |
|----------|--------|
| PHP 실행 파일 | `.php`, `.phar` |
| 실행 스크립트 | `.sh`, `.bat`, `.exe` |
| 설정 파일 | `.env`, `.htaccess`, `.conf` |
| 데이터베이스 파일 | `.sql`, `.db` |
| 압축 파일 (보안 위험) | `.zip`, `.tar`, `.gz` |
---
## 관련 문서
- [template-basics.md](template-basics.md) - 템플릿 기초
- [template-routing.md](template-routing.md) - 템플릿 라우트/언어 파일 규칙
- [template-caching.md](template-caching.md) - 템플릿 캐싱 전략
- [template-commands.md](template-commands.md) - 템플릿 Artisan 커맨드
+685
View File
@@ -0,0 +1,685 @@
# 템플릿 개발 워크플로우
> **위치**: `docs/extension/template-workflow.md`
> **관련 문서**: [template-basics.md](./template-basics.md) | [template-commands.md](./template-commands.md) | [template-development.md](../frontend/template-development.md)
---
## TL;DR (5초 요약)
```text
1. 필수 파일: template.json, routes.json, _base.json, errors/{404,403,500}.json
2. 빌드 설정: package.json, vite.config.ts (IIFE 빌드, terser 대신 esbuild)
3. 검증 순서: JSON 파싱 → layout_name 필수 → error_config → 에러 레이아웃 파일 존재
4. 컴포넌트: 템플릿에 실제 존재하는 것만 import (없는 컴포넌트 import 시 빌드 실패)
5. 설치: php artisan template:build → php artisan template:install → php artisan template:activate
```
---
## 목차
1. [개요](#개요)
2. [템플릿 생성 체크리스트](#템플릿-생성-체크리스트)
3. [Phase 1: 필수 메타데이터 파일](#phase-1-필수-메타데이터-파일)
4. [Phase 2: 레이아웃 파일](#phase-2-레이아웃-파일)
5. [Phase 3: 빌드 설정](#phase-3-빌드-설정)
6. [Phase 4: 컴포넌트 설정](#phase-4-컴포넌트-설정)
7. [Phase 5: 다국어 파일](#phase-5-다국어-파일)
8. [Phase 6: 빌드 및 설치](#phase-6-빌드-및-설치)
9. [검증 로직 이해](#검증-로직-이해)
10. [자주 발생하는 오류와 해결](#자주-발생하는-오류와-해결)
11. [템플릿 개발 Artisan 명령어](#템플릿-개발-artisan-명령어)
---
## 개요
이 문서는 그누보드7 템플릿을 처음부터 만들 때 필요한 **실전 워크플로우**를 정리합니다.
실제 `sirsoft-user_sample` 템플릿 개발 과정에서 겪은 시행착오를 바탕으로 작성되었습니다.
---
## 템플릿 생성 체크리스트
새 템플릿 생성 시 아래 체크리스트를 순서대로 완료합니다:
```
Phase 1: 필수 메타데이터
□ template.json 생성 (error_config 포함)
□ routes.json 생성 (layout_name 필수)
Phase 2: 레이아웃 파일
□ layouts/_user_base.json 또는 layouts/_admin_base.json 생성
□ layouts/home.json (또는 dashboard.json) 생성
□ layouts/errors/404.json 생성
□ layouts/errors/403.json 생성
□ layouts/errors/500.json 생성
Phase 3: 빌드 설정
□ package.json 생성 (build 스크립트 포함)
□ vite.config.ts 생성 (IIFE 빌드, esbuild minify)
□ tsconfig.json 생성
□ tsconfig.node.json 생성
□ tailwind.config.js 생성
□ postcss.config.js 생성
Phase 4: 컴포넌트 설정
□ src/index.ts 생성 (실제 존재하는 컴포넌트만 import)
□ src/handlers/index.ts 생성
□ src/styles/main.css 생성
Phase 5: 다국어 파일
□ lang/ko.json 생성 (errors 섹션 포함)
□ lang/en.json 생성 (errors 섹션 포함)
Phase 6: 빌드 및 설치
□ php artisan template:build [identifier]
□ php artisan template:install [identifier]
□ php artisan template:activate [identifier]
```
---
## Phase 1: 필수 메타데이터 파일
### 1.1 template.json
```json
{
"identifier": "vendor-template_name",
"vendor": "vendor",
"name": {
"ko": "템플릿 한국어 이름",
"en": "Template English Name"
},
"version": "1.0.0",
"description": {
"ko": "템플릿 설명 (한국어)",
"en": "Template description (English)"
},
"type": "user",
"locales": ["ko", "en"],
"author": {
"name": "vendor",
"email": "contact@vendor.com"
},
"g7_version": ">=1.0.0",
"dependencies": {
"modules": {},
"plugins": {}
},
"assets": {
"css": ["assets/css/main.css"],
"js": []
},
"components": {
"basic": ["button", "div", "span", "h1", "h2", "p", "icon"],
"composite": ["header", "footer", "card"],
"layout": ["container", "flex", "grid"]
},
"error_config": {
"layouts": {
"404": "404",
"403": "403",
"500": "500"
}
}
}
```
**필수 항목**:
- `identifier`: 고유 식별자 (vendor-name 형식)
- `type`: "admin" 또는 "user"
- `locales`: 지원 언어 배열
- `error_config.layouts`: 404, 403, 500 매핑
### 1.2 routes.json
```
주의: layout_name 필드가 없으면 설치 실패!
```
```json
{
"version": "1.0.0",
"layout_name": "routes",
"meta": {
"title": "Routes",
"description": "Route definitions for template"
},
"data_sources": [],
"components": [],
"routes": [
{
"path": "/",
"layout": "home",
"auth": false
}
]
}
```
**필수 필드**:
- `layout_name`: DB 저장용 레이아웃 이름 (필수!)
- `routes`: 라우트 정의 배열
---
## Phase 2: 레이아웃 파일
### 2.1 디렉토리 구조
```
templates/_bundled/vendor-template/
└── layouts/
├── _user_base.json # 베이스 레이아웃 (user 템플릿)
├── _admin_base.json # 베이스 레이아웃 (admin 템플릿)
├── home.json # 홈 레이아웃
├── routes.json # 라우트 정의
├── errors/ # 필수 디렉토리
│ ├── 404.json # 필수
│ ├── 403.json # 필수
│ └── 500.json # 필수
└── partials/ # partial 파일 (DB 저장 안됨)
```
### 2.2 베이스 레이아웃 (_user_base.json)
```json
{
"version": "1.0.0",
"layout_name": "_user_base",
"meta": {
"is_base": true
},
"data_sources": [],
"slots": {
"header": [],
"content": [],
"footer": []
}
}
```
### 2.3 에러 레이아웃
**404.json 예시**:
```json
{
"version": "1.0.0",
"layout_name": "404",
"extends": "_user_base",
"meta": {
"title": "$t:errors.404.title",
"is_error_layout": true,
"error_code": 404
},
"data_sources": [],
"slots": {
"content": [
{
"id": "error_container",
"type": "basic",
"name": "Div",
"props": {
"className": "flex flex-col items-center justify-center min-h-[60vh] text-center p-8"
},
"children": [
{
"id": "error_code",
"type": "basic",
"name": "H1",
"props": {
"className": "text-6xl font-bold text-gray-900 dark:text-white mb-4"
},
"text": "404"
},
{
"id": "error_title",
"type": "basic",
"name": "H2",
"props": {
"className": "text-2xl font-semibold text-gray-700 dark:text-gray-300 mb-2"
},
"text": "$t:errors.404.title"
},
{
"id": "error_message",
"type": "basic",
"name": "P",
"props": {
"className": "text-gray-500 dark:text-gray-400 mb-8"
},
"text": "$t:errors.404.message"
},
{
"id": "back_button",
"type": "basic",
"name": "Button",
"props": {
"className": "px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"
},
"text": "$t:errors.back_home",
"actions": [
{
"type": "click",
"handler": "navigate",
"params": { "path": "/" }
}
]
}
]
}
]
}
}
```
**403.json, 500.json**도 동일한 구조로 생성 (error_code와 아이콘만 다름)
---
## Phase 3: 빌드 설정
### 3.1 package.json
```json
{
"name": "vendor-template",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite build --watch"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"@vitejs/plugin-react": "^4.0.0",
"autoprefixer": "^10.4.14",
"postcss": "^8.4.24",
"tailwindcss": "^3.3.2",
"typescript": "^5.0.0",
"vite": "^5.0.0"
}
}
```
### 3.2 vite.config.ts
```
주의: minify는 'esbuild' 사용 (terser는 별도 설치 필요)
필수: process.env.NODE_ENV 정의 (외부 라이브러리 호환성)
```
```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
name: 'VendorTemplate',
formats: ['iife'],
fileName: () => 'components.iife.js',
},
outDir: 'dist',
emptyDirBeforeWrite: true,
minify: 'esbuild', // terser 대신 esbuild 사용!
rollupOptions: {
external: ['react', 'react-dom'],
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
},
});
```
### 3.3 tsconfig.json
```json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
```
### 3.4 tailwind.config.js
```javascript
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{js,ts,jsx,tsx}', './layouts/**/*.json'],
darkMode: 'class',
theme: { extend: {} },
plugins: [],
};
```
### 3.5 postcss.config.js
```javascript
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
```
---
## Phase 4: 컴포넌트 설정
### 4.1 src/index.ts
```
필수: 실제 존재하는 컴포넌트만 import!
존재하지 않는 컴포넌트를 import하면 빌드 실패
```
```typescript
// 실제 존재하는 컴포넌트만 import
import * as basicComponents from './components/basic';
import * as compositeComponents from './components/composite';
import * as layoutComponents from './components/layout';
import { handlerMap } from './handlers';
// 전역 등록
declare global {
interface Window {
G7Core: {
registerComponents: (components: Record<string, unknown>) => void;
registerHandlers: (handlers: Record<string, unknown>) => void;
};
}
}
// 컴포넌트 등록
const allComponents = {
...basicComponents,
...compositeComponents,
...layoutComponents,
};
if (window.G7Core) {
window.G7Core.registerComponents(allComponents);
window.G7Core.registerHandlers(handlerMap);
}
export { allComponents, handlerMap };
```
### 4.2 src/handlers/index.ts
```typescript
export const handlerMap = {
// 커스텀 핸들러 등록
} as const;
export type HandlerName = keyof typeof handlerMap;
```
### 4.3 src/styles/main.css
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```
---
## Phase 5: 다국어 파일
### 5.1 lang/ko.json
```
필수: errors 섹션 필수! (에러 레이아웃에서 참조)
```
```json
{
"site": {
"title": "사이트 제목"
},
"errors": {
"404": {
"title": "페이지를 찾을 수 없습니다",
"message": "요청하신 페이지가 존재하지 않거나 이동되었습니다."
},
"403": {
"title": "접근이 거부되었습니다",
"message": "이 페이지에 접근할 권한이 없습니다."
},
"500": {
"title": "서버 오류",
"message": "서버에 문제가 발생했습니다. 잠시 후 다시 시도해 주세요."
},
"back_home": "홈으로 돌아가기"
}
}
```
### 5.2 lang/en.json
```json
{
"site": {
"title": "Site Title"
},
"errors": {
"404": {
"title": "Page Not Found",
"message": "The page you requested does not exist or has been moved."
},
"403": {
"title": "Access Denied",
"message": "You do not have permission to access this page."
},
"500": {
"title": "Server Error",
"message": "Something went wrong on our end. Please try again later."
},
"back_home": "Back to Home"
}
}
```
---
## Phase 6: 빌드 및 설치
### 6.1 빌드
```bash
php artisan template:build vendor-template
```
### 6.2 설치
```bash
php artisan template:install vendor-template
```
### 6.3 활성화
```bash
php artisan template:activate vendor-template
```
---
## 검증 로직 이해
### 설치 시 자동 검증 순서
1. **JSON 파싱 검증**: 모든 레이아웃 파일의 JSON 유효성
2. **layout_name 필수**: 템플릿 레이아웃은 반드시 `layout_name` 필드 필요
3. **error_config 검증**: `template.json`에 `error_config.layouts` 섹션 필수
4. **에러 레이아웃 검증**: 404, 403, 500 레이아웃 파일 존재 확인
5. **partial 병합 검증**: `partial` 참조 파일 존재 및 순환 참조 확인
### ValidatesLayoutFiles 트레이트
```php
// 스캔 대상 디렉토리
layouts/*.json // ✅ 스캔 (DB 저장)
layouts/errors/*.json // ✅ 스캔 (DB 저장)
layouts/partials/*.json // ❌ 스캔 안 함 (extends로만 참조)
```
### TemplateManager::validateErrorLayouts()
```php
// 필수 에러 코드
$requiredErrorCodes = [404, 403, 500];
// 검증 항목
1. error_config.layouts 섹션 존재
2. 404, 403, 500 키 존재
3. layouts/errors/{code}.json 파일 존재
```
---
## 자주 발생하는 오류와 해결
### 오류 1: layout_name 필드 누락
```
❌ 오류: layout_name 필드가 누락되었습니다
```
**원인**: routes.json 또는 레이아웃 파일에 `layout_name` 필드 없음
**해결**:
```json
{
"layout_name": "routes", // 추가
// ... 나머지 내용
}
```
### 오류 2: 에러 레이아웃 파일 없음
```
❌ 오류: 404 에러 레이아웃 파일을 찾을 수 없습니다
```
**원인**: `layouts/errors/404.json` 파일 없음
**해결**:
1. `layouts/errors/` 디렉토리 생성
2. `404.json`, `403.json`, `500.json` 파일 생성
### 오류 3: terser not found
```
❌ 오류: Cannot find module 'terser'
```
**원인**: vite.config.ts에서 `minify: 'terser'` 설정했지만 terser 미설치
**해결**:
```typescript
// vite.config.ts
build: {
minify: 'esbuild', // terser 대신 esbuild 사용
}
```
### 오류 4: 컴포넌트 import 실패
```
❌ 오류: Module not found: './components/basic/H5'
```
**원인**: 존재하지 않는 컴포넌트를 import
**해결**: 실제 존재하는 컴포넌트만 import
```typescript
// ❌ 잘못된 예
import { H5, H6, Box } from './components/basic'; // H5, H6, Box가 없으면 에러
// ✅ 올바른 예
import { H1, H2, H3, Div, Span } from './components/basic'; // 실제 존재하는 것만
```
### 오류 5: error_config 누락
```
❌ 오류: 에러 페이지 설정(error_config)이 누락되었습니다
```
**원인**: `template.json`에 `error_config` 섹션 없음
**해결**:
```json
{
"error_config": {
"layouts": {
"404": "404",
"403": "403",
"500": "500"
}
}
}
```
---
## 템플릿 개발 Artisan 명령어
| 명령어 | 설명 |
|--------|------|
| `php artisan template:list` | 템플릿 목록 조회 |
| `php artisan template:build [id]` | 템플릿 빌드 |
| `php artisan template:build --all` | 모든 템플릿 빌드 |
| `php artisan template:install [id]` | 템플릿 설치 |
| `php artisan template:activate [id]` | 템플릿 활성화 |
| `php artisan template:deactivate [id]` | 템플릿 비활성화 |
| `php artisan template:uninstall [id]` | 템플릿 삭제 |
| `php artisan template:refresh-layout [id]` | 레이아웃 갱신 (빌드 없이) |
| `php artisan template:cache-clear` | 템플릿 캐시 초기화 |
---
## 관련 문서
- [템플릿 기초](./template-basics.md) - 템플릿 타입, 메타데이터
- [템플릿 커맨드](./template-commands.md) - Artisan 커맨드 상세
- [템플릿 개발 가이드](../frontend/template-development.md) - 컴포넌트 개발
- [레이아웃 JSON 스키마](../frontend/layout-json.md) - 레이아웃 작성법
- [컴포넌트 개발 규칙](../frontend/components.md) - 컴포넌트 작성법