CommunityCodierung & Entwicklunggithub.com

PHP-Entwicklung

PHP 8.0+ Entwicklung mit XAMPP, RESTful APIs, PDO/MySQL/MariaDB und Authentifizierung. Ideal zum Erstellen von PHP-Backends, API-Endpunkten, Konfigurieren von XAMPP oder zur Integration von PHP mit Datenbanken.

Was ist PHP-Entwicklung?

Die Fähigkeit "PHP-Entwicklung" ist ein umfassendes Toolkit für Entwickler, die mit PHP 8.0+ arbeiten. Sie unterstützt die Erstellung sicherer, moderner PHP-Anwendungen, insbesondere mit PDO für Datenbankzugriffe (MySQL/MariaDB), RESTful API-Design und XAMPP-Umgebungskonfiguration. Sie ist für gängige KI-Coding-Assistenten wie GitHub Copilot, Claude Code und Codex optimiert. Die Fähigkeit liefert detaillierte Codebeispiele, Best Practices und Anti-Patterns für die PHP-Entwicklung, einschließlich Sicherheitsmaßnahmen gegen SQL-Injection und XSS. Sie bietet auch ein Prüfprotokoll zur Validierung der Implementierung und behandelt Themen von grundlegenden PHP-8.0-Funktionen (benannte Argumente, Union Types) bis hin zur erweiterten API-Entwicklung mit JSON-Response-Helfern, CORS-Middleware und JWT-basierter Authentifizierung. Diese Fähigkeit ist besonders nützlich für Entwickler, die PHP-Backends erstellen oder Datenbankintegrationen, Authentifizierungssysteme oder RESTful Webdienste implementieren.

Funktioniert mit✓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 Codierung & Entwicklung skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht PHP-Entwicklung?

Optimiert für aktuelle PHP 8.x-Versionen, PHPUnit 11+, Composer 2.x und PDO-basierte MySQL- oder MariaDB-Anwendungen.

Expertenanleitung für die Erstellung qualitativ hochwertiger PHP-Anwendungen mit PHP 8.0+, PDO für sicheren Datenbankzugriff, RESTful API-Design und XAMPP-Umgebungskonfiguration gemäß der offiziellen PHP-Dokumentation unter https://php.net.

  • Nutzung nativer paralleler Unteragenten-Dispatch und 200k+ Kontextfenster, wo verfügbar.

Cross-Client-Portabilität

Diese Fähigkeit wurde entwickelt, um übergreifend mit GitHub Copilot, Claude Code und Codex nutzbar zu sein.

  • GitHub Copilot: Behalten Sie den Ordner in einem für Copilot sichtbaren Skill-Pfad oder betten Sie den Workflow in Projektanweisungen ein, wenn die Ordnersuche nicht verfügbar ist.
  • Claude Code: Behalten Sie den Ordner in einem lokalen Skills-Verzeichnis oder einer kompatiblen Plugin-Quelle.
  • Codex: Installieren oder synchronisieren Sie den Ordner in $CODEX_HOME/skills/php-development und starten Sie Codex nach größeren Änderungen neu.

MCP-Verfügbarkeit und Fallback

Bevorzugter MCP-Server: Keiner erforderlich

  • Fallback-Prompt: "Verwenden Sie die PHP-Entwicklungsfähigkeit ohne MCP. Verlassen Sie sich auf ihre lokalen Anweisungen, gebündelten Ressourcen, Standard-Shell- oder Editor-Werkzeuge und direkte Verifikation. Zeigen Sie die verwendeten Belege vor einer Schlussfolgerung."
  • Behaupten Sie nicht, dass eine MCP-Operation verwendet wurde, wenn der aktive Host sie nicht bereitstellt.
  • Behandeln Sie lokale Dateien, Tests, gerenderte Ausgaben, Protokolle oder Screenshots als Fallback-Belege.

Anti-Patterns

  • Direkte SQL-Interpolation: Prepared Statements sind die Grundlage für Korrektheit und Sicherheit beim PHP-Datenzugriff.
  • Vermischung von Request-Parsing, Geschäftslogik und Rendering: Eng gekoppelte Skripte sind schwerer zu testen und zu APIs weiterzuentwickeln.
  • Annahme, dass Validierung allein XSS verhindert: Ausgabekodierung ist dennoch wichtig, wenn benutzergesteuerter Inhalt zurück in HTML gerendert wird.

Verifikationsprotokoll

Bevor Sie behaupten, "Fähigkeit erfolgreich angewendet":

  1. Bestanden/nicht bestanden: Die PHP-Entwicklungsimplementierung benennt die Ziel-Laufzeit, Framework-Version und betroffenen Dateien.
  2. Bestanden/nicht bestanden: Build, Lint, Test oder äquivalente lokale Validierung wird für die geänderte Oberfläche ausgeführt.
  3. Bestanden/nicht bestanden: Grenzfälle für Fehler, Abhängigkeitsdrift und Umgebungsunterschiede werden adressiert oder explizit ausgeschlossen.
  4. Belastungstest-Szenario: Wenden Sie den Workflow auf eine Änderung an, die Happy-Path-Tests besteht, aber eine Randbedingung verletzt.
  5. Erfolgsmetrik: Keine ungeprüften Erfolgsbehauptungen; jede Implementierungsbehauptung ist einem Befehl oder Artefakt zugeordnet.

Vorher-Nachher-Beispiel

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

// Nachher
$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);

Ersetzt String-Interpolation durch ein Prepared Statement und eine schmalere Ergebnisform.

Aktivierungsbedingungen

Verwenden Sie Symptom -> Aktionsauslöser: Wenn eines zutrifft, wenden Sie diese Fähigkeit an und verifizieren Sie mit dem untenstehenden Protokoll.

Kern-PHP-Entwicklung:

  • Erstellen von PHP-RESTful-APIs mit korrekten HTTP-Methoden
  • Arbeiten mit der XAMPP-Umgebung (Apache + MySQL + PHP)
  • Implementieren sicherer Datenbankoperationen mit PDO
  • Erstellen von Authentifizierungs- und Sitzungsverwaltungssystemen
  • Behandeln von Datei-Uploads und Formularübermittlungen

Datenbank- und Datenschicht:

  • Verbinden von PHP mit MySQL/MariaDB über PDO
  • Schreiben von Prepared Statements zur Verhinderung von SQL-Injection
  • Implementieren von Transaktionshandhabung für Datenintegrität
  • Erstellen von Repository-Mustern für den Datenzugriff
  • Arbeiten mit MySQLi vs. PDO-Vergleichen

Sicherheit & Best Practices:

  • Implementieren von Passwort-Hashing (password_hash, password_verify)
  • Absicherung gegen XSS, CSRF und SQL-Injection
  • Validieren und Bereinigen von Benutzereingaben
  • Verwalten von Sitzungen und Authentifizierungstokens
  • Konfigurieren von CORS-Headern für den API-Zugriff

API-Entwicklung:

  • Entwerfen von RESTful-Endpunkten mit korrekten HTTP-Statuscodes
  • Behandeln von JSON-Anfragen und -Antworten
  • Implementieren von Middleware für Authentifizierung und Autorisierung
  • Fehlerbehandlung und Protokollierung
  • Ratenbegrenzung und API-Versionierung

Teil 1: PHP 8.0+ Grundlagen

Moderne PHP-Funktionen

<?php
// Benannte Argumente (PHP 8.0+)
function createUser(string $name, string $email, bool $isAdmin = false): User {
    return new User($name, $email, $isAdmin);
}

// Aufruf mit benannten Argumenten
$user = createUser(email: '[email protected]', name: 'John Doe');

// Union-Typen (PHP 8.0+)
function processValue(string|int|float $value): string {
    return (string)$value;
}

// Nullsafe-Operator (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Unbekannt';

// Konstruktor-Property-Promotion (PHP 8.0+)
class User {
    public function __construct(
        public string $name,
        public string $email,
        private string $passwordHash
    ) {}
}

Typdeklarationen & Strikte Typen

<?php
declare(strict_types=1); // Erzwingt Typsicherheit

// Typisierte Eigenschaften und Rückgabetypen
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- und Intersection-Typen
function processData(string|array $data): string|int {
    return is_array($data) ? count($data) : strlen($data);
}

Teil 2: PDO-Datenbankintegration

Datenbankverbindungsklasse

<?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("Datenbankverbindung fehlgeschlagen: " . $e->getMessage());
                throw new RuntimeException("Fehler bei der Datenbankverbindung");
            }
        }

        return self::$instance;
    }
}

Prepared Statements für Sicherheit

<?php
class UserRepository {
    private PDO $db;

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

    // Benutzer per E-Mail mit Prepared Statement finden
    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;
    }

    // Neuen Benutzer mit Passwort-Hashing erstellen
    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();
    }

    // Authentifizierung mit Passwortverifikation
    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;
        }

        // Prüfen, ob das Passwort neu gehasht werden muss
        if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
            $newHash = password_hash($password, PASSWORD_DEFAULT);
            $this->updatePasswordHash($user['id'], $newHash);
        }

        unset($user['password_hash']); // Sensible Daten entfernen
        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]);
    }
}

Transaktionsmanagement

<?php
class RecipeService {
    private PDO $db;

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

    // Rezept mit Zutaten, Anleitungen und Bildern in einer Transaktion erstellen
    public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
        try {
            $this->db->beginTransaction();

            // Rezept einfügen
            $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();

            // Zutaten einfügen
            $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,
                ]);
            }

            // Anleitungen einfügen
            $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("Fehler beim Erstellen des Rezepts: " . $e->getMessage());
            throw $e;
        }
    }
}

Teil 3: RESTful API-Entwicklung

JSON-Response-Helfer

<?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 = 'Erfolg'): never {
        self::json([
            'success' => true,
            'message' => $message,
            'data' => $data,
        ]);
    }
}

CORS-Middleware

<?php
// CORS-Header behandeln
$allowedOrigins = [
    'http://localhost:5173', // Vite Entwicklungs-Server
    'http://localhost:3000',  // Alternativer Entwicklungs-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');

// Preflight-Anfragen behandeln
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

Authentifizierungs-Middleware

<?php
function requireAuth(): array {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

    if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        Response::error('Unauthorized: Fehlender oder ungültiger Token', 401);
    }

    $token = $matches[1];

    // Token validieren (Beispiel mit JWT)
    try {
        $payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
        return (array) $payload;
    } catch (Exception $e) {
        Response::error('Unauthorized: Ungültiger Token', 401);
    }
}

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

    if ($user['role'] !== 'admin') {
        Response::error('Forbidden: Admin-Zugriff erforderlich', 403);
    }

    return $user;
}

Teil 4: Erweiterte API-Nutzung

API-Routen-Handler-Beispiel

<?php
// index.php - Einstiegspunkt für API-Aufrufe
require_once __DIR__ . '/../vendor/autoload.php';

header('Content-Type: application/json');

$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];

// Basis-URL bereinigen
$path = parse_url($requestUri, PHP_URL_PATH);
$path = rtrim($path, '/');

// CORS-Header (vor jeder Logik setzen)
require_once __DIR__ . '/../middleware/CorsMiddleware.php';

// Routing-Logik
$routes = [
    'GET' => [
        '/api/users' => 'UserController@index',
        '/api/users/{id}' => 'UserController@show',
        '/api/recipes' => 'RecipeController@index',
        '/api/recipes/{id}' => 'RecipeController@show',
    ],
    'POST' => [
        '/api/users' => 'UserController@store',
        '/api/recipes' => 'RecipeController@store',
        '/api/auth/login' => 'AuthController@login',
    ],
    'PUT' => [
        '/api/users/{id}' => 'UserController@update',
        '/api/recipes/{id}' => 'RecipeController@update',
    ],
    'DELETE' => [
        '/api/users/{id}' => 'UserController@destroy',
        '/api/recipes/{id}' => 'RecipeController@destroy',
    ],
];

// Route abgleichen und Controller aufrufen
// ... (Routing-Implementierung)

Standard-Fehlerantworten

{
  "success": false,
  "error": "Validierung fehlgeschlagen",
  "details": {
    "email": ["Das Feld E-Mail ist erforderlich.", "Das Format der E-Mail ist ungültig."],
    "password": ["Das Passwort muss mindestens 8 Zeichen lang sein."]
  }
}

{
  "success": true,
  "message": "Benutzer erfolgreich erstellt",
  "data": {
    "id": 1,
    "name": "John Doe",
    "email": "[email protected]",
    "role": "user",
    "created_at": "2024-01-15T10:30:00Z"
  }
}

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.

Verwandte Skills