Communityコーディング&開発github.com

PHP 開発 (PHP 8.0+)

PHP 8.0+ 開発 — XAMPP、RESTful API、PDO/MySQL/MariaDB、認証。PHP バックエンドの構築、API エンドポイントの作成、XAMPP の設定、PHP とデータベースの統合を行う際に使用します。

PHP 開発 (PHP 8.0+) とは?

このスキルは、PHP 8.0+ を使用した高品質なアプリケーション開発のための包括的なガイドです。PDO による安全なデータベースアクセス、RESTful API の設計、XAMPP 環境の設定に焦点を当てています。公式 PHP ドキュメント (https://php.net) に従い、プリペアドステートメントによる SQL インジェクション対策、パスワードハッシュ化、トランザクション管理などのセキュリティベストプラクティスを提供します。GitHub Copilot、Claude Code、Codex などの主要な AI エージェントプラットフォームで動作し、MCP サーバーを必要とせず、ローカル検証と直接的な検証をサポートします。また、PHP 8.0 以降の名前付き引数、ユニオン型、Nullsafe 演算子などのモダンな機能も活用します。

対応✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/php-development

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

PHP 開発

現在の PHP 8.x リリース、PHPUnit 11+、Composer 2.x、および PDO ベースの MySQL または MariaDB アプリケーション向けに最適化されています。

PHP 8.0+、安全なデータベースアクセスのための PDO、RESTful API 設計、および XAMPP 環境設定を使用した高品質な PHP アプリケーション構築のための専門ガイダンスを提供します。公式 PHP ドキュメント (https://php.net) に従います。

  • 利用可能な場合は、ネイティブの並列サブエージェントディスパッチと 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 データアクセスにおける正しさとセキュリティのベースラインはプリペアドステートメントです。
  • リクエスト解析、ビジネスルール、レンダリングの混在: 密に結合されたスクリプトはテストが難しく、API に進化させるのも困難です。
  • バリデーションだけで XSS を防げると仮定すること: ユーザー制御のコンテンツが HTML にレンダリングされる場合、出力エンコーディングは依然として重要です。

検証プロトコル

「スキルが正常に適用されました」と主張する前に:

  1. 合格/不合格: PHP 開発の実装では、ターゲットのランタイム、フレームワークのバージョン、影響を受けるファイルを指定します。
  2. 合格/不合格: 変更された範囲に対して、ビルド、リンター、テスト、または同等のローカル検証が実行されます。
  3. 合格/不合格: エラー、依存関係のドリフト、環境の違いに関するエッジケースに対処するか、明示的にスコープ外とします。
  4. ストレステストシナリオ: ハッピーパステストは通過するが、1 つの境界条件で失敗する変更にワークフローを適用します。
  5. 成功メトリクス: 未テストの成功主張はゼロ。すべての実装主張はコマンドまたはアーティファクトにマッピングされます。

変更前後の例

<?php
// 変更前
$stmt = $pdo->query("SELECT * FROM users WHERE email = '$email'");
$user = $stmt->fetch();

// 変更後
$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);

文字列補間をプリペアドステートメントに置き換え、より狭い結果形状にします。

アクティベーション条件

症状 -> アクショントリガーを使用します。条件が一致した場合、このスキルを適用し、以下のプロトコルで検証します。

コア PHP 開発:

  • 適切な HTTP メソッドを使用した PHP RESTful API の構築
  • XAMPP (Apache + MySQL + PHP) 環境での作業
  • PDO を使用した安全なデータベース操作の実装
  • 認証およびセッション管理システムの作成
  • ファイルアップロードとフォーム送信の処理

データベースとデータ層:

  • PDO を使用した PHP から MySQL/MariaDB への接続
  • SQL インジェクションを防ぐためのプリペアドステートメントの作成
  • データ整合性のためのトランザクション処理の実装
  • データアクセスのためのリポジトリパターンの作成
  • MySQLi と PDO の比較

セキュリティとベストプラクティス:

  • パスワードハッシュ化 (password_hash, password_verify) の実装
  • XSS、CSRF、SQL インジェクションからの保護
  • ユーザー入力のバリデーションとサニタイズ
  • セッションと認証トークンの管理
  • API アクセス用の CORS ヘッダーの設定

API 開発:

  • 適切な HTTP ステータスコードを使用した RESTful エンドポイントの設計
  • JSON リクエストとレスポンスの処理
  • 認証と認可のためのミドルウェアの実装
  • エラーハンドリングとロギング
  • レート制限と API バージョニング

パート 1: PHP 8.0+ の基礎

モダンな PHP 機能

<?php
// 名前付き引数 (PHP 8.0+)
function createUser(string $name, string $email, bool $isAdmin = false): User {
    return new User($name, $email, $isAdmin);
}

// 名前付き引数で呼び出し
$user = createUser(email: '[email protected]', name: 'John Doe');

// ユニオン型 (PHP 8.0+)
function processValue(string|int|float $value): string {
    return (string)$value;
}

// Nullsafe 演算子 (PHP 8.0+)
$country = $session?->user?->address?->country ?? '不明';

// コンストラクタのプロパティ昇格 (PHP 8.0+)
class User {
    public function __construct(
        public string $name,
        public string $email,
        private string $passwordHash
    ) {}
}

型宣言と厳格な型

<?php
declare(strict_types=1); // 型の安全性を強制

// 型付きプロパティと戻り値の型
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;
    }
}

// ユニオン型と交差型
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("データベース接続に失敗しました: " . $e->getMessage());
                throw new RuntimeException("データベース接続エラー");
            }
        }

        return self::$instance;
    }
}

セキュリティのためのプリペアドステートメント

<?php
class UserRepository {
    private PDO $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    // プリペアドステートメントでメールアドレスからユーザーを検索
    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;
    }

    // パスワードハッシュ化で新規ユーザーを作成
    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();
    }

    // パスワード検証による認証
    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;
        }

        // パスワードの再ハッシュが必要かチェック
        if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
            $newHash = password_hash($password, PASSWORD_DEFAULT);
            $this->updatePasswordHash($user['id'], $newHash);
        }

        unset($user['password_hash']); // 機密データを削除
        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;
    }

    // トランザクション内で材料、手順、画像を含むレシピを作成
    public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
        try {
            $this->db->beginTransaction();

            // レシピを挿入
            $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();

            // 材料を挿入
            $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,
                ]);
            }

            // 手順を挿入
            $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("レシピの作成に失敗しました: " . $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
// CORS ヘッダーを処理
$allowedOrigins = [
    'http://localhost:5173', // Vite 開発サーバー
    'http://localhost:3000',  // 代替開発サーバー
];

$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');

// プリフライトリクエストを処理
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: トークンが存在しないか無効です', 401);
    }

    $token = $matches[1];

    // トークンを検証 (JWT を使用した例)
    try {
        $payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
        return (array) $payload;
    } catch (Exception $e) {
        Response::error('Unauthorized: 無効なトークンです', 401);
    }
}

function requireAdmin(): array {
    $user = requireAuth();

    if ($user['role'] !== 'admin') {
        Response::error('Forbidden: このリソースにアクセスする権限がありません', 403);
    }

    return $user;
}

RESTful API エンドポイントの例

<?php
require_once 'config/database.php';
require_once 'helpers/response.php';

$db = Database::getInstance();
$userRepo = new UserRepository($db);

// シンプルなルーター
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// GET /api/users - 全ユーザーを取得
if ($method === 'GET' && $path === '/api/users') {
    requireAdmin(); // 管理者のみアクセス可能
    
    $stmt = $db->query("SELECT id, name, email, role, status, created_at FROM user ORDER BY created_at DESC");
    $users = $stmt->fetchAll();
    
    Response::success($users);
}

// POST /api/auth/login - ユーザーログイン
if ($method === 'POST' && $path === '/api/auth/login') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['email']) || !isset($input['password'])) {
        Response::error('メールアドレスとパスワードは必須です', 422);
    }
    
    $user = $userRepo->authenticate($input['email'], $input['password']);
    
    if ($user === null) {
        Response::error('認証情報が無効です', 401);
    }
    
    // トークンを生成 (ここでは簡単な例)
    $token = JWT::encode([
        'user_id' => $user['id'],
        'role' => $user['role'],
        'exp' => time() + 3600
    ], $_ENV['JWT_SECRET']);
    
    Response::success([
        'token' => $token,
        'user' => $user
    ]);
}

パート 4: XAMPP 環境設定

ディレクトリ構造

htdocs/
└── your_project/
    ├── api/              # API エンドポイント
    ├── config/           # 設定ファイル
    ├── helpers/          # ヘルパー関数
    ├── middleware/       # ミドルウェア
    ├── models/           # データベースモデル
    ├── uploads/          # アップロードされたファイル
    ├── public/           # 公開アセット
    │   ├── index.php     # エントリーポイント
    │   ├── .htaccess     # Apache の書き換えルール
    │   └── assets/       # CSS、JS、画像
    ├── logs/             # アプリケーションログ
    └── vendor/           # Composer の依存関係

.htaccess の設定

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

# セキュリティヘッダー
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "DENY"
    Header set X-XSS-Protection "1; mode=block"
</IfModule>

# ディレクトリ一覧表示を無効化
Options -Indexes

php.ini の推奨設定

; エラー報告
error_reporting = E_ALL
display_errors = Off
log_errors = On
error_log = C:/xampp/php/logs/php_error.log

; リソース制限
memory_limit = 256M
upload_max_filesize = 10M
post_max_size = 12M
max_execution_time = 30

; 日付設定
date.timezone = Asia/Tokyo

; セッション設定
session.save_path = C:/xampp/tmp
session.use_strict_mode = 1
session.cookie_httponly = 1
session.cookie_samesite = "Lax"

環境変数 (.env)

# アプリケーション設定
APP_ENV=development
APP_DEBUG=true
APP_URL=http://localhost/your_project

# データベース設定
DB_HOST=localhost
DB_PORT=3306
DB_NAME=recipe_sharing_system
DB_USER=root
DB_PASSWORD=

# JWT 設定
JWT_SECRET=your-secret-key-change-in-production
JWT_EXPIRY=3600

# メール設定
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=tls

Composer の設定 (composer.json)

{
    "name": "your/project",
    "description": "レシピ共有システム",
    "type": "project",
    "require": {
        "php": ">=8.1",
        "vlucas/phpdotenv": "^5.5",
        "firebase/php-jwt": "^6.8"
    },
    "require-dev": {
        "phpunit/phpunit": "^11.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

パート 5: データベーススキーマの例

レシピ共有システム

CREATE DATABASE IF NOT EXISTS recipe_sharing_system
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

USE recipe_sharing_system;

-- ユーザーテーブル
CREATE TABLE user (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('user', 'admin') DEFAULT 'user',
    status ENUM('active', 'inactive', 'banned') DEFAULT 'active',
    profile_image VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- レシピテーブル
CREATE TABLE recipe (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    description TEXT NULL,
    category ENUM('和食', '洋食', '中華', 'エスニック', 'その他') NOT NULL,
    difficulty ENUM('簡単', '普通', '難しい') DEFAULT '普通',
    prep_time INT NOT NULL COMMENT '準備時間(分)',
    cook_time INT NOT NULL COMMENT '調理時間(分)',
    servings INT NOT NULL COMMENT '人数',
    author_id INT NOT NULL,
    status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (author_id) REFERENCES user(id) ON DELETE CASCADE
);

-- 材料テーブル
CREATE TABLE ingredient (
    id INT AUTO_INCREMENT PRIMARY KEY,
    recipe_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    quantity DECIMAL(10, 2) NOT NULL,
    unit VARCHAR(50) NOT NULL,
    sort_order INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (recipe_id) REFERENCES recipe(id) ON DELETE CASCADE
);

-- 手順テーブル
CREATE TABLE instruction (
    id INT AUTO_INCREMENT PRIMARY KEY,
    recipe_id INT NOT NULL,
    step_number INT NOT NULL,
    instruction_text TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (recipe_id) REFERENCES recipe(id) ON DELETE CASCADE
);

パート 6: テスト戦略

PHPUnit の設定とテストの例

XAMPP 環境向けの PHPUnit テストの設定:

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.0/phpunit.xsd"
    bootstrap="vendor/autoload.php"
    colors="true"
    executionOrder="defects"
    failOnRisky="true"
>    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Integration">
            <directory>tests/Integration</directory>
        </testsuite>
    </testsuites>

    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_HOST" value="localhost"/>
        <env name="DB_NAME" value="test_recipe_db"/>
    </php>
</phpunit>

データベーステストの例

<?php
namespace Tests\Integration;

use PHPUnit\Framework\TestCase;
use App\Database;

class UserRepositoryTest extends TestCase
{
    private static PDO $db;
    private UserRepository $userRepo;

    public static function setUpBeforeClass(): void
    {
        // テストデータベースをセットアップ
        self::$db = Database::getInstance();
        self::createTestSchema();
    }

    protected function setUp(): void
    {
        $this->userRepo = new UserRepository(self::$db);
        self::cleanDatabase();
    }

    public function testCreateAndFindUser(): void
    {
        $id = $this->userRepo->create('テスト 太郎', '[email protected]', 'securepassword');
        
        $this->assertIsInt($id);
        $this->assertGreaterThan(0, $id);
        
        $user = $this->userRepo->findByEmail('[email protected]');
        $this->assertNotNull($user);
        $this->assertEquals('テスト 太郎', $user['name']);
    }

    public function testAuthenticationSuccess(): void
    {
        $this->userRepo->create('テスト 太郎', '[email protected]', 'securepassword');
        
        $user = $this->userRepo->authenticate('[email protected]', 'securepassword');
        $this->assertNotNull($user);
        $this->assertArrayNotHasKey('password_hash', $user);
    }

    public function testAuthenticationFailure(): void
    {
        $this->userRepo->create('テスト 太郎', '[email protected]', 'securepassword');
        
        $user = $this->userRepo->authenticate('[email protected]', 'wrongpassword');
        $this->assertNull($user);
    }

    private static function createTestSchema(): void
    {
        self::$db->exec("
            CREATE TABLE IF NOT EXISTS user (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                email VARCHAR(255) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                role ENUM('user', 'admin') DEFAULT 'user',
                status ENUM('active', 'inactive', 'banned') DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            )
        ");
    }

    private static function cleanDatabase(): void
    {
        self::$db->exec("TRUNCATE TABLE user");
    }
}

よくある質問 (FAQ)

Q: PDO と MySQLi ではどちらを使用すべきですか? A: PDO を推奨します。PDO は 12 種類以上のデータベースドライバをサポートしているため、MySQL から PostgreSQL などに切り替える場合でも、コードの変更が最小限で済みます。また、名前付きパラメータをサポートしており、プリペアドステートメントの可読性が向上します。

Q: XAMPP で環境変数を設定するにはどうすればよいですか? A: vlucas/phpdotenv パッケージを使用して .env ファイルから環境変数を読み込むか、xampp/apache/conf/extra/httpd-xampp.conf で Apache の SetEnv ディレクティブを使用します。機密情報をバージョン管理にコミットしないでください。

Q: PHP アプリケーションで CORS エラーを処理するにはどうすればよいですか? A: サーバーから適切な CORS ヘッダーを送信します。Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers を含めます。プリフライトリクエスト (OPTIONS) の場合は、直ちに 200 ステータスで応答します。

Q: PHP アプリケーションのセキュリティを確保するためのベストプラクティスは何ですか? A: データベースクエリには常にプリペアドステートメントを使用し、パスワードを保存する際は password_hash() と password_verify() を使用し、信頼できないデータを出力する際は出力エンコーディングを実装し、htmlspecialchars() を使用して XSS 攻撃を防止し、HTTPS を強制し、フレームワークとライブラリを常に最新の状態に保ってください。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

関連スキル