Community编程与开发github.com

mianhtsys/landingMod3

PHP 8.0+ 开发 — XAMPP、RESTful API、PDO/MySQL/MariaDB 和身份验证。适用于构建 PHP 后端、创建 API 端点、配置 XAMPP 或集成 PHP 与数据库。

landingMod3 是什么?

该技能专为 PHP 8.0+ 开发人员设计,专注于使用 PDO 进行安全数据库访问、RESTful API 设计以及 XAMPP 环境配置。它提供专家级指导,涵盖现代 PHP 特性如命名参数、联合类型和空安全运算符,以及类型声明和严格类型检查。在数据库层面,技能演示了 PDO 连接管理、预处理语句防止 SQL 注入、密码哈希验证和事务处理。此外,还详细介绍了 RESTful API 开发,包括 JSON 响应助手、CORS 中间件和身份验证中间件,帮助开发者构建健壮且安全的 Web 应用程序。该技能适用于 GitHub Copilot、Claude Code 和 Codex,并提供了详细的激活条件、反模式和验证协议,以确保应用成功。

兼容平台✓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 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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 开发技能。依赖其本地指令、捆绑资源、标准 shell 或编辑器工具以及直接验证。在得出结论之前显示所使用的证据。”
  • 当活动主机未暴露 MCP 操作时,不要声称使用了 MCP 操作。
  • 将本地文件、测试、渲染输出、日志或屏幕截图视为回退证据路径。

反模式

  • 直接插值 SQL:预处理语句是 PHP 数据访问正确性和安全性的基准。
  • 混合请求解析、业务规则和渲染:紧密耦合的脚本更难测试和演变为 API。
  • 假设验证可以防止 XSS:当用户控制的内容被渲染回 HTML 时,输出编码仍然很重要。

验证协议

在声称“技能应用成功”之前:

  1. 通过/失败:PHP 开发实现应标明目标运行时、框架版本和受影响的文件。
  2. 通过/失败:对更改的表面运行构建、lint、测试或等效的本地验证。
  3. 通过/失败:处理或明确排除错误、依赖漂移和环境差异的边界情况。
  4. 压力测试场景:将工作流应用于一个通过快乐路径测试但失败一个边界条件的更改。
  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;
}

// 空安全运算符 (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Unknown';

// 构造函数属性提升 (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 = '成功'): 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('未授权:缺少或无效的令牌', 401);
    }

    $token = $matches[1];

    // 验证令牌(示例使用 JWT)
    try {
        $payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
        return (array) $payload;
    } catch (Exception $e) {
        Response::error('未授权:无效的令牌', 401);
    }
}

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

    if ($user['role'] !== 'admin') {
        Response::error('禁止:需要管理员权限', 403);
    }

    return $user;
}

第 4 部分:XAMPP 环境设置

目录结构

htdocs/
├── project-root/
│   ├── public/              # Web 根目录
│   │   └── index.php
│   ├── src/                 # 源代码
│   │   └── ...
│   ├── config/              # 配置文件
│   │   └── database.php
│   ├── vendor/              # Composer 依赖
│   └── .htaccess            # Apache 配置

Apache 配置(.htaccess)

RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]

数据库初始化

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',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

验证检查清单

  • PHP 版本 >= 8.0
  • 使用 declare(strict_types=1);
  • 未使用已弃用的 PHP 函数
  • PDO 已配置异常模式和关联获取
  • 所有数据库查询均使用预处理语句
  • 密码使用 password_hash() 和 password_verify() 处理
  • API 端点包含 CORS 标头
  • 请求和响应使用 JSON 格式
  • 错误已正确处理并记录
  • 配置从环境变量读取

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.

相关技能