Desenvolvimento PHP

Desenvolvimento PHP 8.0+ — XAMPP, APIs RESTful, PDO/MySQL/MariaDB e autenticação. Use ao construir backends PHP, criar endpoints de API, configurar XAMPP ou integrar PHP com bancos de dados.

O que é Desenvolvimento PHP?

Esta habilidade oferece orientação especializada para construir aplicações PHP de alta qualidade usando PHP 8.0+, PDO para acesso seguro a banco de dados, design de APIs RESTful e configuração do ambiente XAMPP, seguindo a documentação oficial do PHP em https://php.net. Ela é projetada para ser portável entre GitHub Copilot, Claude Code e Codex, utilizando despacho paralelo nativo de subagentes e janelas de contexto de 200k+ quando disponíveis. A habilidade enfatiza práticas modernas como prepared statements, tipos estritos, promoção de propriedades de construtor e gerenciamento de transações, enquanto previne anti-padrões como interpolação direta de SQL e código fortemente acoplado. Para desenvolvedores PHP que trabalham com XAMPP, APIs RESTful, autenticação e integração com banco de dados, esta skill fornece exemplos práticos e um protocolo de verificação rigoroso para garantir implementações corretas e seguras.

Funciona com✓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 Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Desenvolvimento PHP faz?

Otimizado para as versões atuais do PHP 8.x, PHPUnit 11+, Composer 2.x e aplicações MySQL ou MariaDB com PDO.

Orientação especializada para construir aplicações PHP de alta qualidade com PHP 8.0+, PDO para acesso seguro a banco de dados, design de APIs RESTful e configuração do ambiente XAMPP, seguindo a documentação oficial do PHP em https://php.net.

  • Aproveite o despacho paralelo nativo de subagentes e janelas de contexto de 200k+ quando disponíveis.

Portabilidade entre Clientes

Esta habilidade foi escrita para permanecer utilizável em GitHub Copilot, Claude Code e Codex.

  • GitHub Copilot: mantenha a pasta em um caminho de habilidades visível pelo Copilot ou envolva o fluxo de trabalho em instruções do projeto quando a descoberta de pasta não estiver disponível.
  • Claude Code: mantenha a pasta em um diretório de habilidades local ou em uma fonte de plugin compatível.
  • Codex: instale ou sincronize a pasta em $CODEX_HOME/skills/php-development e reinicie o Codex após grandes alterações.

Disponibilidade e Fallback do MCP

Servidor MCP Preferido: Nenhum necessário

  • Prompt de fallback: "Use a habilidade de Desenvolvimento PHP sem MCP. Confie em suas instruções locais, recursos agrupados, ferramentas padrão do shell ou editor e verificação direta. Mostre a evidência usada antes de concluir."
  • Não afirme que uma operação MCP foi usada quando o host ativo não a expõe.
  • Trate arquivos locais, testes, saídas renderizadas, logs ou capturas de tela como o caminho de evidência de fallback.

Anti-Padrões

  • Interpolação direta de SQL: Prepared statements são a base para correção e segurança no acesso a dados PHP.
  • Misturar análise de requisição, regras de negócio e renderização: Scripts fortemente acoplados são mais difíceis de testar e evoluir para APIs.
  • Assumir que a validação sozinha previne XSS: A codificação de saída ainda é importante quando conteúdo controlado pelo usuário é renderizado de volta para HTML.

Protocolo de Verificação

Antes de afirmar "habilidade aplicada com sucesso":

  1. Aprovado/reprovado: A implementação de Desenvolvimento PHP nomeia o runtime alvo, a versão do framework e os arquivos afetados.
  2. Aprovado/reprovado: Build, lint, teste ou validação local equivalente é executada para a superfície alterada.
  3. Aprovado/reprovado: Casos de borda para erros, desvio de dependência e diferenças de ambiente são tratados ou explicitamente fora do escopo.
  4. Cenário de teste de pressão: Aplique o fluxo de trabalho a uma alteração que passa nos testes de caminho feliz mas falha em uma condição de limite.
  5. Métrica de sucesso: Zero alegações de sucesso não testadas; toda alegação de implementação mapeia para um comando ou artefato.

Exemplo Antes e Depois

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

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

Substitui a interpolação de string por um prepared statement e uma forma de resultado mais restrita.

Condições de Ativação

Use gatilhos de sintoma -> ação: quando um corresponder, aplique esta habilidade e verifique com o protocolo abaixo.

Desenvolvimento PHP Principal:

  • Construir APIs RESTful PHP com métodos HTTP adequados
  • Trabalhar com ambiente XAMPP (Apache + MySQL + PHP)
  • Implementar operações seguras de banco de dados com PDO
  • Criar sistemas de autenticação e gerenciamento de sessão
  • Lidar com uploads de arquivos e envios de formulário

Banco de Dados e Camada de Dados:

  • Conectar PHP ao MySQL/MariaDB com PDO
  • Escrever prepared statements para prevenir injeção SQL
  • Implementar gerenciamento de transações para integridade de dados
  • Criar padrões de repositório para acesso a dados
  • Trabalhar com comparações MySQLi vs PDO

Segurança e Melhores Práticas:

  • Implementar hashing de senhas (password_hash, password_verify)
  • Proteger contra XSS, CSRF e injeção SQL
  • Validar e sanitizar entrada do usuário
  • Gerenciar sessões e tokens de autenticação
  • Configurar cabeçalhos CORS para acesso à API

Desenvolvimento de API:

  • Projetar endpoints RESTful com códigos de status HTTP adequados
  • Lidar com requisições e respostas JSON
  • Implementar middleware para autenticação e autorização
  • Tratamento de erros e logging
  • Limitação de taxa e versionamento de API

Parte 1: Fundamentos PHP 8.0+

Recursos Modernos do PHP

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

// Chamada com argumentos nomeados
$user = createUser(email: '[email protected]', name: 'John Doe');

// Tipos união (PHP 8.0+)
function processValue(string|int|float $value): string {
    return (string)$value;
}

// Operador nullsafe (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Desconhecido';

// Promoção de propriedades de construtor (PHP 8.0+)
class User {
    public function __construct(
        public string $name,
        public string $email,
        private string $passwordHash
    ) {}
}

Declarações de Tipo e Tipos Estritos

<?php
declare(strict_types=1); // Impõe segurança de tipo

// Propriedades tipadas e tipos de retorno
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;
    }
}

// Tipos união e interseção
function processData(string|array $data): string|int {
    return is_array($data) ? count($data) : strlen($data);
}

Parte 2: Integração com Banco de Dados PDO

Classe de Conexão com Banco de Dados

<?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("Falha na conexão com o banco de dados: " . $e->getMessage());
                throw new RuntimeException("Erro de conexão com o banco de dados");
            }
        }

        return self::$instance;
    }
}

Prepared Statements para Segurança

<?php
class UserRepository {
    private PDO $db;

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

    // Encontrar usuário por email com 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;
    }

    // Criar novo usuário com hashing de senha
    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();
    }

    // Autenticação com verificação de senha
    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;
        }

        // Verificar se a senha precisa de 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']); // Remover dados sensíveis
        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]);
    }
}

Gerenciamento de Transações

<?php
class RecipeService {
    private PDO $db;

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

    // Criar receita com ingredientes, instruções e imagens em uma transação
    public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
        try {
            $this->db->beginTransaction();

            // Inserir receita
            $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();

            // Inserir ingredientes
            $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,
                ]);
            }

            // Inserir instruções
            $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("Falha ao criar receita: " . $e->getMessage());
            throw $e;
        }
    }
}

Parte 3: Desenvolvimento de API RESTful

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

Middleware CORS

<?php
// Lidar com cabeçalhos CORS
$allowedOrigins = [
    'http://localhost:5173', // Servidor de desenvolvimento Vite
    'http://localhost:3000',  // Servidor de desenvolvimento alternativo
];

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

// Lidar com requisições preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

Middleware de Autenticação

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

    if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        Response::error('Não autorizado: Token ausente ou inválido', 401);
    }

    $token = $matches[1];

    // Validar token (exemplo com JWT)
    try {
        $payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
        return (array) $payload;
    } catch (Exception $e) {
        Response::error('Não autorizado: Token inválido', 401);
    }
}

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

    if ($user['role'] !== 'admin') {
        Response::error('Proibido: Acesso de admin necessário', 403);
    }

    return $user;
}

API RESTful CRUD Completa

<?php
require_once 'Database.php';
require_once 'UserRepository.php';
require_once 'RecipeService.php';
require_once 'Response.php';

// Roteamento de requisições
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = rtrim($uri, '/');

// Configuração do banco de dados
try {
    $db = Database::getInstance();
} catch (RuntimeException $e) {
    Response::error('Erro interno do servidor', 500);
}

// Rotas de autenticação
if ($uri === '/api/auth/register' && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (empty($data['name']) || empty($data['email']) || empty($data['password'])) {
        Response::error('Campos obrigatórios ausentes: nome, email, senha', 422);
    }

    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        Response::error('Formato de email inválido', 422);
    }

    if (strlen($data['password']) < 8) {
        Response::error('A senha deve ter pelo menos 8 caracteres', 422);
    }

    $userRepo = new UserRepository($db);

    // Verificar se o email já está em uso
    if ($userRepo->findByEmail($data['email'])) {
        Response::error('Email já registrado', 409);
    }

    try {
        $userId = $userRepo->create($data['name'], $data['email'], $data['password']);
        Response::success(['user_id' => $userId], 'Usuário registrado com sucesso');
    } catch (Exception $e) {
        Response::error('Falha no registro', 500);
    }
}

if ($uri === '/api/auth/login' && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (empty($data['email']) || empty($data['password'])) {
        Response::error('Email e senha são obrigatórios', 422);
    }

    $userRepo = new UserRepository($db);
    $user = $userRepo->authenticate($data['email'], $data['password']);

    if ($user === null) {
        Response::error('Credenciais inválidas', 401);
    }

    // Gerar token JWT
    $token = JWT::encode([
        'user_id' => $user['id'],
        'role' => $user['role'],
        'exp' => time() + 3600,
    ], $_ENV['JWT_SECRET'], 'HS256');

    Response::success([
        'token' => $token,
        'user' => $user,
    ], 'Login bem-sucedido');
}

// Rotas de receitas (protegidas por autenticação)
if ($uri === '/api/recipes' && $method === 'GET') {
    requireAuth();

    $stmt = $db->prepare(
        "SELECT r.id, r.title, r.category, r.difficulty, r.prep_time, r.cook_time, r.servings, r.created_at, u.name as author_name
         FROM recipe r
         JOIN user u ON r.author_id = u.id
         WHERE r.status = 'approved'
         ORDER BY r.created_at DESC"
    );
    $stmt->execute();
    $recipes = $stmt->fetchAll();

    Response::success($recipes);
}

if ($uri === '/api/recipes' && $method === 'POST') {
    $user = requireAuth();
    $data = json_decode(file_get_contents('php://input'), true);

    $recipeService = new RecipeService($db);

    try {
        $recipeId = $recipeService->createRecipeWithDetails(
            array_merge($data, ['authorId' => $user['user_id']]),
            $data['ingredients'] ?? [],
            $data['instructions'] ?? []
        );
        Response::success(['recipe_id' => $recipeId], 'Receita criada com sucesso');
    } catch (Exception $e) {
        Response::error('Falha ao criar receita', 500);
    }
}

// Remover tratamento de rota para requisições inválidas
Response::error('Rota não encontrada', 404);

Parte 4: Configuração do XAMPP

Configuração do Apache

# httpd-vhosts.conf - Host virtual para desenvolvimento local
<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs/recipe-sharing-system/public"
    ServerName recipe-sharing.local

    <Directory "C:/xampp/htdocs/recipe-sharing-system/public">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog "logs/recipe-sharing-error.log"
    CustomLog "logs/recipe-sharing-access.log" combined
</VirtualHost>
# .htaccess - Reescrita de URL para front controller
RewriteEngine On

# Redirecionar todas as requisições para index.php a menos que o arquivo ou diretório exista
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Configuração do PHP

; php.ini - Configurações recomendadas para desenvolvimento
; Habilita exibição de erros para desenvolvimento
display_errors = On
display_startup_errors = On
error_reporting = E_ALL

; Upload de arquivo
file_uploads = On
upload_max_filesize = 10M
post_max_size = 12M
max_file_uploads = 20

; Limites de tempo
max_execution_time = 30
max_input_time = 60
memory_limit = 256M

; Configurações de sessão
session.save_handler = files
session.save_path = "C:/xampp/tmp"
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_httponly = 1
session.cookie_secure = 1  ; Habilite apenas se usar HTTPS
session.cookie_samesite = "Lax"

; Configurações de data e hora
date.timezone = "America/Sao_Paulo"

Parte 5: Testes com PHPUnit

Configuração do PHPUnit

<?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"
>   
    <testsuites>
        <testsuite name="Recipe Sharing System Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>

    <source>
        <include>
            <directory>src</directory>
        </include>
    </source>

    <php>
        <env name="DB_HOST" value="localhost"/>
        <env name="DB_NAME" value="recipe_sharing_system_test"/>
        <env name="DB_USER" value="root"/>
        <env name="DB_PASSWORD" value=""/>
        <env name="JWT_SECRET" value="test_secret_key_2024"/>
    </php>
</phpunit>

Testes para Repositório de Usuário

<?php
use PHPUnit\Framework\TestCase;

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

    protected function setUp(): void {
        $host = $_ENV['DB_HOST'] ?? 'localhost';
        $dbname = $_ENV['DB_NAME'] ?? 'recipe_sharing_system_test';
        $username = $_ENV['DB_USER'] ?? 'root';
        $password = $_ENV['DB_PASSWORD'] ?? '';

        $this->db = new PDO(
            "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
            $username,
            $password,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]
        );

        // Criar tabelas de teste
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS user (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(255) NOT NULL,
                email VARCHAR(255) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                role VARCHAR(50) DEFAULT 'user',
                status VARCHAR(50) DEFAULT 'active',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            )
        ");

        $this->userRepo = new UserRepository($this->db);
    }

    protected function tearDown(): void {
        $this->db->exec("DROP TABLE IF EXISTS user");
        $this->db = null;
    }

    public function testCreateUser(): void {
        $userId = $this->userRepo->create('João Silva', '[email protected]', 'senha_segura_123');

        $this->assertIsInt($userId);
        $this->assertGreaterThan(0, $userId);
    }

    public function testFindByEmail(): void {
        $this->userRepo->create('Maria Santos', '[email protected]', 'outra_senha_456');

        $user = $this->userRepo->findByEmail('[email protected]');

        $this->assertNotNull($user);
        $this->assertEquals('Maria Santos', $user['name']);
        $this->assertArrayHasKey('password_hash', $user);
    }

    public function testAuthenticateWithValidCredentials(): void {
        $password = 'minha_senha_123';
        $this->userRepo->create('Carlos Lima', '[email protected]', $password);

        $user = $this->userRepo->authenticate('[email protected]', $password);

        $this->assertNotNull($user);
        $this->assertEquals('Carlos Lima', $user['name']);
        $this->assertArrayNotHasKey('password_hash', $user); // Dados sensíveis removidos
    }

    public function testAuthenticateWithInvalidPassword(): void {
        $this->userRepo->create('Ana Costa', '[email protected]', 'senha_correta');

        $user = $this->userRepo->authenticate('[email protected]', 'senha_errada');

        $this->assertNull($user);
    }

    public function testAuthenticateWithNonExistentEmail(): void {
        $user = $this->userRepo->authenticate('[email protected]', 'qualquer_senha');

        $this->assertNull($user);
    }

    public function testCreateUserWithDuplicateEmail(): void {
        $this->expectException(PDOException::class);

        $this->userRepo->create('Usuário Um', '[email protected]', 'senha_1');
        $this->userRepo->create('Usuário Dois', '[email protected]', 'senha_2');
    }
}

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.

Habilidades Relacionadas