Saltar al contenido
Skillpedia
Programación general48 mil · #5895

php

Qué hace

Esta guía enseña a escribir código PHP de forma más eficiente y moderna. Muestra mejores formas de organizar datos, gestionar errores y usar funciones recientes del lenguaje para que tu código sea más claro y seguro.

Cuándo usarla

  • ✓Cuando estás aprendiendo a programar en PHP.
  • ✓Cuando revisas o mejoras código PHP que ya existe.
  • ✓Cuando quieres usar las versiones más recientes y eficientes de PHP.

Link de la skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/php/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/php/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo hacer que mi código PHP sea más seguro al manejar datos?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

La guía compara ejemplos de código 'malo' con ejemplos 'buenos' para ilustrar las buenas prácticas. Se centra en usar funciones específicas del lenguaje y características modernas para simplificar tareas comunes.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

PHP: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for php.

Table of Contents

  1. Arrays & Collections
  2. Type Safety
  3. Error Handling
  4. String Handling
  5. OOP & Modern PHP
  6. Functions & Closures
  7. Anti-patterns specific to PHP

1. Arrays & Collections {#arrays}

// ❌ Manual accumulation
$result = [];
foreach ($items as $item) {
    if ($item->isActive()) {
        $result[] = strtoupper($item->getName());
    }
}

// ✅
$result = array_map(
    fn($i) => strtoupper($i->getName()),
    array_filter($items, fn($i) => $i->isActive())
);
// ❌ Manual key-value grouping
$grouped = [];
foreach ($items as $item) {
    $grouped[$item->getCategory()][] = $item;
}

// ✅ (PHP 8.1+) — or use the loop above; PHP lacks a built-in groupBy
// The foreach is actually idiomatic PHP for grouping. No need to force array_* here.
// ❌ Checking isset then accessing
if (isset($data['key'])) {
    $value = $data['key'];
} else {
    $value = 'default';
}

// ✅
$value = $data['key'] ?? 'default';
// ❌ array_push for single element
array_push($items, $newItem);

// ✅
$items[] = $newItem;

Use array_map/array_filter for transforms. The foreach loop is fine when array functions would be less readable.


2. Type Safety {#types}

// ❌ No type declarations
function process($items) {
    return $items;
}

// ✅ (PHP 8.0+)
function process(array $items): array {
    return $items;
}
// ❌ Union type for nullable
function find(string $key): string|null { ... }

// ✅
function find(string $key): ?string { ... }
// ❌ Loose comparison
if ($value == '0') { ... } // true for 0, '', false, null

// ✅
if ($value === '0') { ... }
// ❌ Type checking with gettype()
if (gettype($x) === 'integer') { ... }

// ✅
if (is_int($x)) { ... }
// or with union types, avoid checks entirely

Enable declare(strict_types=1) at the top of every file.


3. Error Handling {#errors}

// ❌ Suppressing errors with @
$data = @file_get_contents($path);

// ✅
$data = file_get_contents($path);
if ($data === false) {
    throw new RuntimeException("Failed to read: $path");
}
// ❌ Catching \Exception and swallowing
try { process(); }
catch (\Exception $e) { /* silence */ }

// ✅
try {
    process();
} catch (SpecificException $e) {
    $this->logger->error($e->getMessage(), ['exception' => $e]);
    throw new AppException('Processing failed', previous: $e);
}
// ❌ Returning mixed types for error indication
function divide(int $a, int $b): int|false {
    if ($b === 0) return false;
    return intdiv($a, $b);
}

// ✅ — throw exception for exceptional cases
function divide(int $a, int $b): int {
    if ($b === 0) throw new \DivisionByZeroError();
    return intdiv($a, $b);
}

4. String Handling {#strings}

// ❌ Concatenation for variable interpolation
$msg = 'Hello, ' . $name . '! You have ' . $count . ' messages.';

// ✅
$msg = "Hello, {$name}! You have {$count} messages.";
// ❌ Manual string contains check
if (strpos($haystack, $needle) !== false) { ... }

// ✅ (PHP 8.0+)
if (str_contains($haystack, $needle)) { ... }
// ❌ substr for prefix/suffix check
if (substr($str, 0, 4) === 'http') { ... }
if (substr($str, -4) === '.php') { ... }

// ✅ (PHP 8.0+)
if (str_starts_with($str, 'http')) { ... }
if (str_ends_with($str, '.php')) { ... }

5. OOP & Modern PHP {#oop}

// ❌ Manual constructor property assignment
class User {
    private string $name;
    private int $age;
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

// ✅ (PHP 8.0+)
class User {
    public function __construct(
        private readonly string $name,
        private readonly int $age,
    ) {}
}
// ❌ Constants as class properties
class Status {
    const ACTIVE = 'active';
    const INACTIVE = 'inactive';
}

// ✅ (PHP 8.1+)
enum Status: string {
    case Active = 'active';
    case Inactive = 'inactive';
}
// ❌ instanceof chains
if ($shape instanceof Circle) { ... }
elseif ($shape instanceof Rectangle) { ... }

// ✅ (PHP 8.0+)
$area = match(true) {
    $shape instanceof Circle => $shape->radius ** 2 * M_PI,

…
Preguntas frecuentes

¿Qué son los 'Arrays y Colecciones'?

Son formas de organizar y manipular listas de datos en PHP. La guía muestra cómo usar funciones integradas en lugar de escribir bucles manuales, para que el código sea más corto y legible.

¿Qué es la 'Type Safety' (seguridad de tipos)?

Consiste en asegurarse de que las variables y funciones usen los tipos de dato correctos (como números o texto). Esto ayuda a evitar errores inesperados en el programa.

¿Por qué evitar el '@' para silenciar errores?

El símbolo '@' oculta problemas que deberían corregirse. Es mejor dejar que el error aparezca y gestionarlo bien, para entender qué pasó y arreglar el código.

Detalles

Descripción original del autor

Language-specific super-code guidelines for php.

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#5895
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas