All skills
asyrafhussin avatar

/php-best-practices

@e7ea05d

PHP 8.x modern patterns, PSR standards, and SOLID principles. Use when reviewing PHP code, checking type safety, auditing code quality, or ensuring PHP best practices. Triggers on "review PHP", "check PHP code", "audit PHP", or "PHP best practices".

Use this Skill: https://skilld.dev/gh/asyrafhussin/agent-skills/php-best-practices

This session only. Nothing lands on disk.

rulespsr-12-coding-style.md

≈1.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

PSR-12 Coding Style

Follow PSR-12 extended coding style for consistent, readable code.

Bad Example

<?php
namespace App\Services;
use App\Models\User;use App\Repositories\UserRepository;

class UserService{
    private $repository;

    public function __construct(UserRepository $repo){
        $this->repository=$repo;
    }

    public function find($id){
        if($id<1){return null;}
        return $this->repository->find($id);
    }

    public function create($data)
    {
        if(!isset($data['email'])||!isset($data['name'])){throw new \Exception('Missing data');}
        return $this->repository->create($data);
    }
}

Good Example

<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\User;
use App\Repositories\UserRepository;
use InvalidArgumentException;

class UserService
{
    public function __construct(
        private UserRepository $repository,
    ) {}

    public function find(int $id): ?User
    {
        if ($id < 1) {
            return null;
        }

        return $this->repository->find($id);
    }

    public function create(array $data): User
    {
        if (!isset($data['email']) || !isset($data['name'])) {
            throw new InvalidArgumentException('Missing required data');
        }

        return $this->repository->create($data);
    }

    public function update(
        int $id,
        array $data,
        bool $validate = true,
    ): User {
        $user = $this->find($id);

        if ($user === null) {
            throw new UserNotFoundException($id);
        }

        if ($validate) {
            $this->validate($data);
        }

        return $this->repository->update($user, $data);
    }
}

Key PSR-12 Rules

<?php

declare(strict_types=1);

namespace App\Example;

use App\Contracts\ServiceInterface;
use App\Exceptions\CustomException;
use Psr\Log\LoggerInterface;

// One blank line after namespace and use blocks
class ExampleService implements ServiceInterface
{
    // Opening brace on its own line for classes
    private const MAX_RETRIES = 3;

    public function __construct(
        private LoggerInterface $logger,
        private int $timeout = 30,
    ) {
        // Constructor body
    }

    // One blank line between methods
    public function process(
        string $input,
        array $options = [],
    ): string {
        // Multi-line: closing paren, return type, and brace on same line
        $result = '';

        // Space after control structure keywords
        if ($input === '') {
            return $result;
        }

        // Operators surrounded by spaces
        $length = strlen($input) + 1;

        // Foreach with proper spacing
        foreach ($options as $key => $value) {
            $result .= "{$key}: {$value}\n";
        }

        // Switch statement formatting
        switch ($input[0]) {
            case 'a':
                $result = 'starts with a';
                break;
            case 'b':
                $result = 'starts with b';
                break;
            default:
                $result = 'other';
                break;
        }

        // Try-catch formatting
        try {
            $this->validate($input);
        } catch (CustomException $e) {
            $this->logger->error($e->getMessage());
            throw $e;
        } finally {
            $this->cleanup();
        }

        return $result;
    }

    // Closure formatting
    public function withCallback(callable $callback): array
    {
        $items = [1, 2, 3];

        // Short closure
        $doubled = array_map(fn($n) => $n * 2, $items);

        // Multi-line closure
        $processed = array_filter(
            $items,
            function (int $item) use ($callback): bool {
                return $callback($item) > 0;
            }
        );

        return $processed;
    }
}

Interface and Trait

<?php

declare(strict_types=1);

namespace App\Contracts;

interface ServiceInterface
{
    public function process(string $input, array $options = []): string;

    public function withCallback(callable $callback): array;
}

trait LoggableTrait
{
    protected function log(string $message): void
    {
        // Trait method implementation
    }
}

Why

  • Consistency: All code looks the same regardless of author
  • Readability: Standardized formatting is easier to read
  • Tooling: PHP CS Fixer and IDE formatters can enforce automatically
  • Collaboration: Reduces friction in code reviews
  • Industry Standard: Most PHP projects and frameworks follow PSR-12
  • Professionalism: Demonstrates attention to code quality

Source: SKILL.md on GitHub

No alerts17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill is a comprehensive and safe resource for PHP 8.x best practices. It provides structured guidance on type safety, modern PHP syntax, PSR standards, and secure coding practices (such as prepared statements and password hashing). The agent is instructed to use standard environment detection commands (php -v, grep) to tailor its advice. No malicious patterns or security risks were identified.

  • Socket17d

    No alerts

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer6mo

    39 files scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at e7ea05d. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last month.

Steadyupdated 7 months ago
Other metadata
metadata
{
  "author": "php-community",
  "version": "2.1.0",
  "phpVersion": "8.0 - 8.5"
}

README badge

README badge for asyrafhussin/agent-skills/php-best-practices