PHP로 동적 UI를 만드는 주요 방법들을 설명해드릴게요:
1. 조건문을 이용한 동적 UI
php
<?php $user_role = "admin"; // 동적으로 변경 가능 if ($user_role === "admin") { echo '<button class="admin-btn">관리자 메뉴</button>'; echo '<div class="admin-panel">관리자 전용 콘텐츠</div>'; } else { echo '<button class="user-btn">일반 메뉴</button>'; } ?>
2. 데이터베이스 연동 동적 UI
php
<?php // 데이터베이스에서 메뉴 데이터 가져오기 $menu_items = [ ['title' => '홈', 'url' => '/'], ['title' => '소개', 'url' => '/about'], ['title' => '연락처', 'url' => '/contact'] ]; ?> <nav> <ul> <?php foreach ($menu_items as $item): ?> <li> <a href="<?= $item['url'] ?>"> <?= htmlspecialchars($item['title']) ?> </a> </li> <?php endforeach; ?> </ul> </nav>
3. 폼 처리와 동적 콘텐츠
php
<?php $message = ""; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? ''; if (!empty($name)) { $message = "안녕하세요, {$name}님!"; } else { $message = "이름을 입력해주세요."; } } ?> <form method="POST"> <input type="text" name="name" placeholder="이름을 입력하세요"> <button type="submit">제출</button> </form> <?php if (!empty($message)): ?> <div class="message"><?= htmlspecialchars($message) ?></div> <?php endif; ?>
4. 템플릿 시스템 활용
php
<?php function renderCard($title, $content, $type = 'default') { $class = "card card-{$type}"; return " <div class='{$class}'> <h3>{$title}</h3> <p>{$content}</p> </div> "; } // 동적으로 카드 생성 echo renderCard('제목1', '내용1', 'primary'); echo renderCard('제목2', '내용2', 'secondary'); ?>
5. AJAX와 결합한 동적 UI
php
// api.php <?php if (isset($_GET['action']) && $_GET['action'] === 'get_users') { $users = [ ['id' => 1, 'name' => '김철수'], ['id' => 2, 'name' => '이영희'] ]; header('Content-Type: application/json'); echo json_encode($users); exit; } ?> <!-- index.html --> <script> async function loadUsers() { const response = await fetch('api.php?action=get_users'); const users = await response.json(); users.forEach(user => { document.getElementById('user-list').innerHTML += `<div class="user-item">${user.name}</div>`; }); } </script>
6. 컴포넌트 기반 접근법
php
<?php class UIComponent { public static function button($text, $variant = 'primary') { return "<button class='btn btn-{$variant}'>{$text}</button>"; } public static function alert($message, $type = 'info') { return "<div class='alert alert-{$type}'>{$message}</div>"; } } // 사용 예시 echo UIComponent::button('저장하기', 'success'); echo UIComponent::alert('저장되었습니다!', 'success'); ?>
7. 세션/쿠키 기반 동적 UI
php
<?php session_start(); // 사용자 테마 설정 if (isset($_POST['theme'])) { $_SESSION['theme'] = $_POST['theme']; } $current_theme = $_SESSION['theme'] ?? 'light'; ?> <body class="theme-<?= $current_theme ?>"> <form method="POST"> <select name="theme" xxxxonchange="this.form.submit()"> <option value="light" <?= $current_theme === 'light' ? 'selected' : '' ?>>라이트</option> <option value="dark" <?= $current_theme === 'dark' ? 'selected' : '' ?>>다크</option> </select> </form> </body>
주요 팁:
보안: htmlspecialchars()로 XSS 방지
분리: HTML과 PHP 로직 분리 유지
재사용: 컴포넌트화하여 코드 재사용성 높이기
성능: 캐싱 전략 활용 (APC, Redis 등)
이러한 방법들을 조합하면 PHP로 풍부한 동적 UI를 만들 수 있습니다!