PHP 개발
최신 PHP 8.x 릴리스, PHPUnit 11+, Composer 2.x 및 PDO 기반 MySQL 또는 MariaDB 애플리케이션에 최적화되었습니다.
PHP 8.0+, 안전한 데이터베이스 접근을 위한 PDO, RESTful API 설계, 그리고 공식 PHP 문서(https://php.net)에 따른 XAMPP 환경 구성에 대한 전문 지침을 통해 고품질 PHP 애플리케이션을 구축하세요.
- 가능한 경우 기본 병렬 하위 에이전트 디스패치와 200k+ 컨텍스트 윈도우를 활용하세요.
크로스 클라이언트 이식성
이 스킬은 GitHub Copilot, Claude Code, Codex에서 사용할 수 있도록 작성되었습니다.
- GitHub Copilot: 폴더를 Copilot이 인식 가능한 스킬 경로에 배치하거나, 폴더 검색이 불가능한 경우 워크플로우를 프로젝트 지침에 포함시키세요.
- Claude Code: 폴더를 로컬 스킬 디렉토리 또는 호환 가능한 플러그인 소스에 배치하세요.
- Codex: 폴더를
$CODEX_HOME/skills/php-development에 설치하거나 동기화하고, 주요 변경 후 Codex를 재시작하세요.
MCP 가용성 및 폴백
선호 MCP 서버: 필요 없음
- 폴백 프롬프트: "MCP 없이 PHP 개발 스킬을 사용하세요. 로컬 명령어, 번들 리소스, 표준 셸 또는 편집기 도구, 직접 검증에 의존하세요. 결론을 내리기 전에 사용된 증거를 보여주세요."
- 활성 호스트가 MCP를 노출하지 않는 경우 MCP 작업이 사용되었다고 주장하지 마세요.
- 로컬 파일, 테스트, 렌더링된 출력, 로그 또는 스크린샷을 폴백 증거 경로로 취급하세요.
안티 패턴
- SQL 직접 인터폴레이션: PHP 데이터 접근의 정확성과 보안을 위해 Prepared Statement가 기준입니다.
- 요청 파싱, 비즈니스 규칙, 렌더링 혼합: 결합도가 높은 스크립트는 테스트가 어렵고 API로 발전시키기 어렵습니다.
- 검증만으로 XSS를 방지한다고 가정: 사용자 제어 콘텐츠가 HTML로 렌더링될 때 출력 인코딩이 여전히 중요합니다.
검증 프로토콜
"스킬 적용 성공"을 주장하기 전에:
- 통과/실패: PHP 개발 구현이 대상 런타임, 프레임워크 버전 및 영향받는 파일을 지정합니다.
- 통과/실패: 변경된 부분에 대해 빌드, 린트, 테스트 또는 이에 상응하는 로컬 검증이 실행됩니다.
- 통과/실패: 오류, 종속성 드리프트 및 환경 차이에 대한 엣지 케이스가 처리되거나 명시적으로 범위를 벗어난 것으로 표시됩니다.
- 압박 테스트 시나리오: 해피 패스 테스트를 통과하지만 하나의 경계 조건에서 실패하는 변경에 워크플로우를 적용합니다.
- 성공 메트릭: 테스트되지 않은 성공 주장이 없어야 합니다. 모든 구현 주장은 명령 또는 아티팩트에 매핑됩니다.
전후 예시
<?php
// Before
$stmt = $pdo->query("SELECT * FROM users WHERE email = '$email'");
$user = $stmt->fetch();
// After
$stmt = $pdo->prepare('SELECT id, email, password_hash FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
문자열 인터폴레이션을 Prepared Statement로 대체하고 결과 형태를 좁혔습니다.
활성화 조건
증상 -> 작업 트리거 사용: 일치하는 항목이 있으면 이 스킬을 적용하고 아래 프로토콜로 검증하세요.
핵심 PHP 개발:
- 적절한 HTTP 메서드를 사용한 PHP RESTful API 구축
- XAMPP(Apache + MySQL + PHP) 환경 작업
- PDO를 사용한 안전한 데이터베이스 작업 구현
- 인증 및 세션 관리 시스템 생성
- 파일 업로드 및 양식 제출 처리
데이터베이스 및 데이터 계층:
- PDO를 사용한 PHP와 MySQL/MariaDB 연결
- SQL 인젝션 방지를 위한 Prepared Statement 작성
- 데이터 무결성을 위한 트랜잭션 처리 구현
- 데이터 접근을 위한 리포지토리 패턴 생성
- MySQLi와 PDO 비교 작업
보안 및 모범 사례:
- 비밀번호 해싱(password_hash, password_verify) 구현
- XSS, CSRF 및 SQL 인젝션 방지
- 사용자 입력 검증 및 정화
- 세션 및 인증 토큰 관리
- API 접근을 위한 CORS 헤더 구성
API 개발:
- 적절한 HTTP 상태 코드를 사용한 RESTful 엔드포인트 설계
- JSON 요청 및 응답 처리
- 인증 및 권한 부여를 위한 미들웨어 구현
- 오류 처리 및 로깅
- 속도 제한 및 API 버전 관리
파트 1: PHP 8.0+ 기초
최신 PHP 기능
<?php
// Named arguments (PHP 8.0+)
function createUser(string $name, string $email, bool $isAdmin = false): User {
return new User($name, $email, $isAdmin);
}
// Call with named arguments
$user = createUser(email: '[email protected]', name: 'John Doe');
// Union types (PHP 8.0+)
function processValue(string|int|float $value): string {
return (string)$value;
}
// Nullsafe operator (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
private string $passwordHash
) {}
}
타입 선언 및 엄격한 타입
<?php
declare(strict_types=1); // Enforce type safety
// Typed properties and return types
class Recipe {
private int $id;
private string $title;
private ?DateTime $createdAt;
public function __construct(int $id, string $title) {
$this->id = $id;
$this->title = $title;
}
public function getTitle(): string {
return $this->title;
}
public function setCreatedAt(?DateTime $date): void {
$this->createdAt = $date;
}
}
// Union and intersection types
function processData(string|array $data): string|int {
return is_array($data) ? count($data) : strlen($data);
}
파트 2: PDO 데이터베이스 통합
데이터베이스 연결 클래스
<?php
class Database {
private static ?PDO $instance = null;
public static function getInstance(): PDO {
if (self::$instance === null) {
$host = $_ENV['DB_HOST'] ?? 'localhost';
$dbname = $_ENV['DB_NAME'] ?? 'recipe_sharing_system';
$username = $_ENV['DB_USER'] ?? 'root';
$password = $_ENV['DB_PASSWORD'] ?? '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
try {
self::$instance = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
error_log("Database connection failed: " . $e->getMessage());
throw new RuntimeException("Database connection error");
}
}
return self::$instance;
}
}
보안을 위한 Prepared Statement
<?php
class UserRepository {
private PDO $db;
public function __construct(PDO $db) {
$this->db = $db;
}
// Find user by email with prepared statement
public function findByEmail(string $email): ?array {
$stmt = $this->db->prepare(
"SELECT id, email, password_hash, role, status
FROM user
WHERE email = :email LIMIT 1"
);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch();
return $user ?: null;
}
// Create new user with password hashing
public function create(string $name, string $email, string $password): int {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare(
"INSERT INTO user (name, email, password_hash, role, status, created_at, updated_at)
VALUES (:name, :email, :password_hash, 'user', 'active', NOW(), NOW())"
);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password_hash', $passwordHash, PDO::PARAM_STR);
$stmt->execute();
return (int) $this->db->lastInsertId();
}
// Authentication with password verification
public function authenticate(string $email, string $password): ?array {
$user = $this->findByEmail($email);
if ($user === null) {
return null;
}
if (!password_verify($password, $user['password_hash'])) {
return null;
}
// Check if password needs rehash
if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
$this->updatePasswordHash($user['id'], $newHash);
}
unset($user['password_hash']); // Remove sensitive data
return $user;
}
private function updatePasswordHash(int $userId, string $hash): void {
$stmt = $this->db->prepare(
"UPDATE user SET password_hash = :hash WHERE id = :id"
);
$stmt->execute([':hash' => $hash, ':id' => $userId]);
}
}
트랜잭션 관리
<?php
class RecipeService {
private PDO $db;
public function __construct(PDO $db) {
$this->db = $db;
}
// Create recipe with ingredients, instructions, and images in a transaction
public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
try {
$this->db->beginTransaction();
// Insert recipe
$stmt = $this->db->prepare(
"INSERT INTO recipe (title, description, category, difficulty, prep_time, cook_time, servings, author_id, status, created_at, updated_at)
VALUES (:title, :description, :category, :difficulty, :prep_time, :cook_time, :servings, :author_id, 'pending', NOW(), NOW())"
);
$stmt->execute([
':title' => $recipeData['title'],
':description' => $recipeData['description'],
':category' => $recipeData['category'],
':difficulty' => $recipeData['difficulty'],
':prep_time' => $recipeData['prepTime'],
':cook_time' => $recipeData['cookTime'],
':servings' => $recipeData['servings'],
':author_id' => $recipeData['authorId'],
]);
$recipeId = (int) $this->db->lastInsertId();
// Insert ingredients
$ingredientStmt = $this->db->prepare(
"INSERT INTO ingredient (recipe_id, name, quantity, unit, sort_order, created_at, updated_at)
VALUES (:recipe_id, :name, :quantity, :unit, :sort_order, NOW(), NOW())"
);
foreach ($ingredients as $index => $ingredient) {
$ingredientStmt->execute([
':recipe_id' => $recipeId,
':name' => $ingredient['name'],
':quantity' => $ingredient['quantity'],
':unit' => $ingredient['unit'],
':sort_order' => $index,
]);
}
// Insert instructions
$instructionStmt = $this->db->prepare(
"INSERT INTO instruction (recipe_id, step_number, instruction_text, created_at, updated_at)
VALUES (:recipe_id, :step_number, :instruction_text, NOW(), NOW())"
);
foreach ($instructions as $index => $instruction) {
$instructionStmt->execute([
':recipe_id' => $recipeId,
':step_number' => $index + 1,
':instruction_text' => $instruction['text'],
]);
}
$this->db->commit();
return $recipeId;
} catch (Exception $e) {
$this->db->rollBack();
error_log("Failed to create recipe: " . $e->getMessage());
throw $e;
}
}
}
파트 3: RESTful API 개발
JSON 응답 헬퍼
<?php
class Response {
public static function json(mixed $data, int $statusCode = 200): never {
http_response_code($statusCode);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
exit;
}
public static function error(string $message, int $statusCode = 400): never {
self::json([
'success' => false,
'error' => $message,
], $statusCode);
}
public static function success(mixed $data = null, string $message = 'Success'): never {
self::json([
'success' => true,
'message' => $message,
'data' => $data,
]);
}
}
CORS 미들웨어
<?php
// Handle CORS headers
$allowedOrigins = [
'http://localhost:5173', // Vite dev server
'http://localhost:3000', // Alternative dev server
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins, true)) {
header("Access-Control-Allow-Origin: $origin");
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
인증 미들웨어
<?php
function requireAuth(): array {
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
Response::error('Unauthorized: Missing or invalid token', 401);
}
$token = $matches[1];
// Validate token (example withJWT)
try {
$payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
return (array) $payload;
} catch (Exception $e) {
Response::error('Unauthorized: Invalid token', 401);
}
}
function requireAdmin(): array {
$user = requireAuth();
if ($user['role'] !== 'admin') {
Response::error('Forbidden: Admin access required', 403);
}
return $user;
}
파트 4: 오류 처리 및 로깅
전역 예외 핸들러
<?php
function exceptionHandler(Throwable $exception): void {
error_log(sprintf(
"Uncaught %s: %s in %s on line %d",
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
));
$statusCode = ($exception instanceof HttpException) ? $exception->getStatusCode() : 500;
$message = $_ENV['APP_ENV'] === 'production' ? 'Internal Server Error' : $exception->getMessage();
Response::error($message, $statusCode);
}
set_exception_handler('exceptionHandler');
입력 검증 예시
<?php
trait ValidationTrait {
public function validateEmail(string $email): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function sanitizeString(string $input): string {
return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}
public function validateRecipeData(array $data): array {
$errors = [];
if (empty($data['title']) || strlen($data['title']) > 255) {
$errors['title'] = 'Title is required and must be under 255 characters';
}
if (!in_array($data['category'] ?? null, ['appetizer', 'main', 'dessert'], true)) {
$errors['category'] = 'Invalid category';
}
return $errors;
}
}
파트 5: 배포 및 모범 사례
Composer 설정
{
"name": "your-app/recipe-sharing",
"require": {
"php": ">=8.0",
"ext-pdo": "*",
"ext-mbstring": "*"
},
"require-dev": {
"phpunit/phpunit": "^11.0",
"phpstan/phpstan": "^1.10"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
환경 변수 (.env)
DB_HOST=localhost
DB_NAME=recipe_sharing_system
DB_USER=root
DB_PASSWORD=
JWT_SECRET=your-secret-key-change-in-production
APP_ENV=development
XAMPP 구성 (php.ini 권장)
; Error reporting
error_reporting = E_ALL
display_errors = On
display_startup_errors = On
; File uploads
upload_max_filesize = 10M
post_max_size = 12M
; Session
session.use_strict_mode = 1
session.cookie_httponly = 1
session.cookie_secure = 1
; Timezone
date.timezone = UTC
요약
이 PHP 개발 스킬은 PHP 8.0+ 애플리케이션을 구축하기 위한 모범 사례, 코드 예시 및 구성을 제공합니다. 핵심 주제는 다음과 같습니다:
- PDO를 포함한 보안 데이터베이스 접근 및 Prepared Statement
- RESTful API 설계 및 JSON 응답
- 인증 및 권한 부여 (비밀번호 해싱, JWT)
- 오류 처리 및 로깅
- XAMPP 환경 설정
적절한 HTTP 메서드, 상태 코드 및 미들웨어를 사용하여 모든 API 엔드포인트를 구성하세요. SQL 인젝션을 방지하기 위해 PDO에서 항상 Prepared Statement를 사용하고, 안전한 비밀번호 저장을 위해 password_hash()를 사용하세요.