К основному содержанию
скилл CX Codex

php-expert — скилл для Claude Code: PHP и установка

Скилл php-expert для Claude Code задаёт агенту правила работы с PHP 8+, Laravel, Composer и PHPUnit. Охватывает разработку, тестирование и ревью современного PHP-кода.

Apache-2.0 269 установок ★ 45 обновлён 2026-10-12

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add personamanagmentlayer/pcl --skill php-expert -a claude-code
Открыть на GitHub

Что делает php-expert

php-expert настраивает агент для работы с PHP 8+ и современным объектно-ориентированным кодом. Он охватывает строгую типизацию, типы параметров и свойств, пространства имён, PSR-4, конструкторное внедрение зависимостей, enums, атрибуты и другие возможности PHP 8+.

Скилл также описывает работу с Laravel, Composer и PHPUnit: feature- и unit-тесты, фабрики, проверку ответов API, авторизацию, валидацию и связи моделей. Для команд доступны Read, Write, Edit, а через Bash разрешены команды php, composer и artisan.

Скилл рассчитан на PHP 8+, поэтому проекты на более ранней версии выходят за его заявленную область.

Какие задачи решает

  • написать код на PHP 8+ с типизацией
  • собрать feature- и unit-тесты в PHPUnit
  • настроить фабрики моделей Laravel
  • разобрать зависимости Composer
  • проверить код на PSR-стандарты и типичные анти-паттерны

Примеры запросов агенту

  • Разбери этот сервис на PHP 8+ и добавь строгую типизацию.
  • Напиши для Laravel feature-тесты PHPUnit для создания и обновления поста.
  • Проверь зависимости composer.json и предложи исправления в коде по PSR-4 и PSR-12.

Как установить php-expert

1Через Skills CLI (Vercel)

npx skills add personamanagmentlayer/pcl --skill php-expert -a claude-code

2Вручную: положить файлы

~/.claude/skills/php-expert/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/php-expert/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о php-expert

Как установить php-expert в Claude Code?

Выполните npx skills add personamanagmentlayer/pcl --skill php-expert -a claude-code, затем проверьте файл ~/.claude/skills/php-expert/SKILL.md.

Что делает php-expert?

Скилл помогает писать и проверять современный PHP-код, включая проекты на Laravel, работу с Composer и тесты PHPUnit. Он также задаёт практики строгой типизации, внедрения зависимостей и PSR.

Какие инструменты доступны php-expert?

Скилл использует Read, Write и Edit. Через Bash он работает с командами php, composer и artisan.

Исходный текст

SKILL.md · Apache-2.0
---
name: php-expert
version: 1.1.0
description: >-
  Expert-level PHP development with PHP 8+, Laravel, Composer, and modern best practices.
  Use when the user mentions Laravel, Composer, Symfony, PHPUnit, or PSR standards, or when
  the task involves PHP 8+ Features, Object-Oriented PHP, Modern PHP, or Constructor
  Property Promotion.
category: languages
tags: [php, laravel, composer, symfony, phpunit, psr]
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash(php:*, composer:*, artisan:*)
---

# PHP Expert

Expert guidance for modern PHP development including PHP 8+ features, Laravel framework, Composer dependency management, and PHP best practices.

## Core Concepts

### PHP 8+ Features

- Union types and mixed type
- Named arguments
- Attributes (annotations)
- Constructor property promotion
- Match expressions
- Nullsafe operator
- JIT compiler
- Fibers (PHP 8.1+)
- Readonly properties and classes

### Object-Oriented PHP

- Classes and objects
- Interfaces and abstract classes
- Traits
- Namespaces
- Autoloading (PSR-4)
- Type declarations
- Visibility modifiers

### Modern PHP

- Strict types
- Return type declarations
- Property type declarations
- Enums (PHP 8.1+)
- First-class callable syntax

## Testing with PHPUnit

### Feature Tests

```php
<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PostControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_list_posts(): void
    {
        Post::factory()->count(3)->create(['published' => true]);
        Post::factory()->create(['published' => false]);

        $response = $this->getJson('/api/posts');

        $response->assertOk()
            ->assertJsonCount(3, 'data');
    }

    public function test_can_create_post_when_authenticated(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user, 'api')
            ->postJson('/api/posts', [
                'title' => 'Test Post',
                'content' => 'Test content with enough characters to pass validation.',
            ]);

        $response->assertCreated()
            ->assertJsonPath('data.title', 'Test Post');

        $this->assertDatabaseHas('posts', [
            'title' => 'Test Post',
            'user_id' => $user->id,
        ]);
    }

    public function test_cannot_create_post_when_not_authenticated(): void
    {
        $response = $this->postJson('/api/posts', [
            'title' => 'Test Post',
            'content' => 'Test content',
        ]);

        $response->assertUnauthorized();
    }

    public function test_validates_post_creation(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user, 'api')
            ->postJson('/api/posts', [
                'title' => '', // Invalid
                'content' => 'Short', // Too short
            ]);

        $response->assertUnprocessable()
            ->assertJsonValidationErrors(['title', 'content']);
    }

    public function test_can_update_own_post(): void
    {
        $user = User::factory()->create();
        $post = Post::factory()->create(['user_id' => $user->id]);

        $response = $this->actingAs($user, 'api')
            ->putJson("/api/posts/{$post->id}", [
                'title' => 'Updated Title',
                'content' => 'Updated content with enough characters.',
            ]);

        $response->assertOk();
        $this->assertDatabaseHas('posts', [
            'id' => $post->id,
            'title' => 'Updated Title',
        ]);
    }

    public function test_cannot_update_other_user_post(): void
    {
        $user = User::factory()->create();
        $otherUser = User::factory()->create();
        $post = Post::factory()->create(['user_id' => $otherUser->id]);

        $response = $this->actingAs($user, 'api')
            ->putJson("/api/posts/{$post->id}", [
                'title' => 'Updated Title',
            ]);

        $response->assertForbidden();
    }
}
```

### Unit Tests

```php
<?php

namespace Tests\Unit;

use App\Models\User;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_has_posts(): void
    {
        $user = User::factory()->create();
        $posts = Post::factory()->count(3)->create(['user_id' => $user->id]);

        $this->assertCount(3, $user->posts);
        $this->assertTrue($user->posts->contains($posts->first()));
    }

    public function test_is_admin_returns_true_for_admin_users(): void
    {
        $admin = User::factory()->create(['is_admin' => true]);
        $user = User::factory()->create(['is_admin' => false]);

        $this->assertTrue($admin->isAdmin());
        $this->assertFalse($user->isAdmin());
    }
}
```

### Factories

```php
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'user_id' => User::factory(),
            'title' => fake()->sentence(),
            'slug' => fake()->slug(),
            'content' => fake()->paragraphs(5, true),
            'excerpt' => fake()->paragraph(),
            'published' => false,
            'published_at' => null,
            'tags' => fake()->words(3),
        ];
    }

    public function published(): static
    {
        return $this->state(fn (array $attributes) => [
            'published' => true,
            'published_at' => now(),
        ]);
    }

    public function withUser(User $user): static
    {
        return $this->state(fn (array $attributes) => [
            'user_id' => $user->id,
        ]);
    }
}
```

## Best Practices

### Type Safety

```php
<?php
declare(strict_types=1);

// Always use strict types
// Use type declarations for parameters and return types
// Use property types where possible
```

### Dependency Injection

```php
<?php

// Use constructor injection
class UserService
{
    public function __construct(
        private UserRepository $repository,
        private EventDispatcher $dispatcher,
    ) {}

    public function createUser(array $data): User
    {
        $user = $this->repository->create($data);
        $this->dispatcher->dispatch(new UserCreated($user));
        return $user;
    }
}
```

### PSR Standards

- PSR-1: Basic Coding Standard
- PSR-4: Autoloading Standard
- PSR-12: Extended Coding Style
- PSR-7: HTTP Message Interface

## Anti-Patterns to Avoid

❌ **Not using strict types**: Always declare(strict_types=1)
❌ **Fat controllers**: Extract logic to services
❌ **N+1 queries**: Use eager loading
❌ **No type declarations**: Use types everywhere
❌ **Ignoring PSR standards**: Follow PSR-4, PSR-12
❌ **Direct DB queries in controllers**: Use repositories
❌ **Missing validation**: Always validate input
❌ **No tests**: Write tests for critical code

## Reference Documentation

Detailed material lives alongside this skill and is read on demand:

- [Laravel Framework](references/LARAVEL_FRAMEWORK.md) — Models, Controllers, Form Requests, API Resources, Eloquent Queries, Migrations, Jobs (Queues), Events and Listeners
- [Modern PHP 8+ Syntax](references/MODERN_PHP_8_SYNTAX.md) — Constructor Property Promotion, Named Arguments, Union Types and Mixed, Match Expression, Nullsafe Operator, Attributes (Annotations), Enums (PHP 8.1+), Readonly Properties and Classes

## Resources

- PHP Documentation: https://www.php.net/docs.php
- Laravel Documentation: https://laravel.com/docs
- Composer: https://getcomposer.org/
- PSR Standards: https://www.php-fig.org/psr/
- PHPUnit: https://phpunit.de/

© personamanagmentlayer · Apache-2.0 · personamanagmentlayer/pcl

Похожие скиллы

Все скиллы по теме «Языки программирования» →
php-pro https://github.com/Jeffallan Скилл php-pro задаёт правила разработки на PHP 8.3+ для Laravel и Symfony: включает strict_types, анализ в PHPStan на уровне 9 и тесты PHPUnit или Pest. CX Codex +1 16 400установок appwrite-php appwrite Скилл appwrite-php подсказывает агенту, как писать серверный PHP под Appwrite: пользователи, таблицы, файлы, функции. Пригодится в Laravel и Symfony. CX Codex +1 898установок php-mcp-server-generator официальный github Скилл php-mcp-server-generator для GitHub Copilot генерирует PHP-проект MCP-сервера с инструментами, ресурсами, промптами и тестами. Собирает основу сервера под свои задачи. CX Codex +1 8 900установок php-development Mindrally Скилл php-development для Claude Code, Codex, Cursor и других агентов, который задаёт стиль PHP 8+ с типизацией, PSR-12 и SOLID. Генерирует код с declare(strict_types=1), PHPDoc-блоками и prepared statements. CX Codex +1 1 100установок php-software-architect-expert Giuseppe Trisciuoglio php-software-architect-expert — субагент для Claude Code, который разбирает архитектуру PHP-проектов. Его подключают для проверки Clean Architecture, DDD и решений по структуре кода. CX Codex ★ 372звёзд репо php-refactor-expert Giuseppe Trisciuoglio Субагент php-refactor-expert разбирает PHP-код и предлагает рефакторинг с сохранением поведения. Запускайте его после реализации функции или когда код трудно читать и поддерживать. CX Codex ★ 372звёзд репо

Из того же набора104

Весь набор →
openapi-expert Скилл openapi-expert проектирует спецификации OpenAPI 3.0 и 3.1, настраивает полиморфизм схем и генерирует код клиентов или серверов. CX Codex +1 282установок git-expert Скилл git-expert для Claude Code даёт агенту рецепты для git: отмены коммита, извлечения работы из main и чистки истории. Разбирает проблемы с git, возникшие посреди работы. CX Codex +1 279установок python-expert Скилл python-expert настраивает ИИ-ассистента на разработку на современном Python: строгая типизация, стандарты PEP 8, асинхронный код, работа с uv, poetry и ruff. CX Codex +1 277установок redis-expert Скилл redis-expert для Claude Code помогает проектировать Redis-кэш, pub/sub и работу с потоками данных. Помогает добавлять Redis в приложение и разбирать его архитектуру. CX Codex +1 272установок grafana-expert Скилл grafana-expert превращает агента в инженера по Grafana: дашборды из JSON, переменные, алерты и провижининг в Kubernetes. CX Codex +1 266установок research-expert Скилл research-expert для ИИ-агентов: рабочий код для дизайна исследования и статистики плюс разделы про научное письмо. CX Codex +1 256установок helm-expert Скилл helm-expert для Claude Code помогает разрабатывать Helm-чарты и управлять релизами Kubernetes. Подключается к задачам с чартами, шаблонами и развёртыванием. CX Codex +1 251установок cpp-expert Скилл cpp-expert для Claude Code помогает писать и чинить код на современном C++: C++20/23, STL, владение памятью, конкурентность и CMake. CX Codex +1 250установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой