PHP DEVELOPMENT

Claude Code for PHP Developers

Laravel, Symfony, WordPress, PHP 8.x features, Composer, PHPUnit — complete workflows and 40+ ready-to-paste prompts.

Why Claude Code Works Well for PHP

PHP powers over 75% of the web — WordPress, Laravel, Magento, Drupal, and millions of custom applications. Claude Code understands PHP's ecosystem deeply: Composer dependency management, PSR standards, the major frameworks, and the modern PHP 8.x type system. Whether you're building Laravel APIs, Symfony microservices, WooCommerce plugins, or vanilla PHP libraries, Claude Code speeds up every part of your workflow.

Framework Intelligence

Claude Code understands Laravel's service container, facades, Artisan, Eloquent, and Blade. It knows Symfony's DI container, Doctrine, Messenger, and API Platform. It never mixes up framework-specific idioms.

PHP 8.x Modern Features

Enums, fibers, readonly properties, union/intersection types, named arguments, match expressions, nullsafe operator, first-class callables — Claude Code uses modern PHP by default.

Security by Default

Prepared statements with PDO and $wpdb->prepare, input sanitization, output escaping, CSRF protection via Laravel/Symfony or wp_verify_nonce — Claude Code writes secure PHP without being asked.

Test Coverage

PHPUnit data providers, Mockery mocks, Laravel Feature/Unit test classes, Pest PHP fluent syntax, database transaction rollbacks — full test suites on demand.

Setting Up CLAUDE.md for PHP

Claude Code reads your CLAUDE.md before every session. A good PHP CLAUDE.md removes ambiguity about which framework, PHP version, and tooling you use.

# CLAUDE.md — PHP Project

## Stack
- PHP 8.3, Laravel 11
- MySQL 8 (dev: SQLite in-memory for tests)
- Queue: Redis via Laravel Horizon
- Cache: Redis (Laravel Cache facade)

## Commands
- Run tests: php artisan test --parallel
- Fix code style: ./vendor/bin/pint
- Static analysis: ./vendor/bin/phpstan analyse --level=8
- Start dev server: php artisan serve
- Run queue worker: php artisan horizon

## Architecture
- Service layer in app/Services/ (no business logic in controllers)
- Repository pattern in app/Repositories/
- API resources in app/Http/Resources/
- Jobs in app/Jobs/, Events in app/Events/
- Custom Artisan commands in app/Console/Commands/

## Do not modify
- database/migrations/ — create new migrations instead
- storage/ — generated files
- vendor/ — Composer managed
- bootstrap/cache/ — auto-generated

## Testing conventions
- Unit tests: tests/Unit/ with mocked dependencies
- Feature tests: tests/Feature/ using RefreshDatabase trait
- Use Factories for model creation in tests

Laravel Prompts (copy-paste ready)

ELOQUENT

"Write an Eloquent query that fetches orders with their user, line items, and product names. Filter by user ID and date range, paginate at 20 per page, use eager loading to avoid N+1, and return a typed collection. Include a scope for active orders only."

API RESOURCE

"Generate a full CRUD API for a Product model: FormRequest classes with validation rules, JsonResource with conditional relationship loading, RESTful controller using invokable actions, route group with Sanctum auth, and PHPUnit feature tests covering 422 validation errors and 200 happy paths."

JOBS & QUEUES

"Create a dispatchable Job that sends a welcome email, retries up to 3 times with exponential backoff, handles failures by logging to a dead-letter table, and can be dispatched after a delay. Add a unit test that asserts the job is dispatched with the right arguments."

POLICY & GATES

"Add authorization for this Post model: a Policy class with view, create, update, delete, and restore methods. Include a before hook for admin users. Register the policy in AuthServiceProvider and add ability checks to the controller. Write a test that confirms non-owners cannot update."

MIGRATIONS

"Generate a migration that adds a status column (enum: pending, active, suspended) to the users table with a default of active, a foreign key to a new user_settings table, and a composite index on (status, created_at). Make the migration reversible."

EVENTS

"Set up a domain event system: an OrderPlaced event, a SendOrderConfirmation listener that emails the customer, a UpdateInventory listener that queues stock reduction, and a Notification for the admin dashboard. Use event discovery and test the full flow."

ARTISAN

"Create an Artisan command php artisan reports:generate that accepts a --from and --to date option, generates a CSV report of orders grouped by status, stores it in storage/app/reports/, and sends it via email using a Mailable. Add a progress bar for long-running reports."

MIDDLEWARE

"Write a middleware that rate-limits API requests per user using Redis (60 req/min), returns a 429 with Retry-After header when exceeded, exempts admin users, and logs suspicious burst patterns. Register it as a named middleware in bootstrap/app.php."

BLADE

"Create a Blade component for a paginated data table: accepts a $rows collection and $columns config array, renders a sortable header with query string persistence, shows an empty state slot, and includes a Livewire-compatible wire:click hook for row selection."

SERVICE LAYER

"Extract this controller method into a Service class: accept a DTO as input, validate business rules (throw domain exceptions), persist via the repository, dispatch events, and return a response DTO. Write unit tests for each validation branch."

Symfony Prompts

DOCTRINE

"Create a Doctrine entity for Invoice with a composite primary key, a ManyToMany relationship to Tag, and a OneToMany to InvoiceLine. Add DQL query in a repository that fetches invoices with totals computed in SQL, filtering by date and status. Use QueryBuilder for pagination."

MESSENGER

"Implement CQRS with Symfony Messenger: a CreateOrderCommand with handler, an OrderCreatedEvent that triggers two async handlers (SendConfirmation and UpdateStats). Configure a separate transport for each handler, add retry with backoff, and write an integration test."

API PLATFORM

"Configure an API Platform resource for Product: custom operations with validation groups, a state provider that uses a repository, a state processor for create/update logic, DTO input/output classes, and JWT authentication via LexikJWTAuthenticationBundle. Include OpenAPI documentation."

SECURITY

"Set up Symfony Security with a custom authenticator: JWT token extraction from Authorization header, user provider that loads from Doctrine, roles-based access control with IS_GRANTED in controllers, a voter for resource ownership, and tests for each access scenario."

CONSOLE

"Write a Symfony Console command that processes a CSV file in batches of 500 rows, shows a ProgressBar, validates each row against a Validator constraint, persists valid rows via Doctrine (bulk insert with clear() every batch to avoid memory leaks), and outputs a summary table."

WordPress Development Prompts

PLUGIN

"Create a WordPress plugin following the Plugin Boilerplate pattern: custom post type 'testimonial' with meta fields, a shortcode to display them, a settings page in wp-admin with sanitized options, and REST API endpoints secured with a custom permission callback."

GUTENBERG BLOCK

"Register a Gutenberg block using block.json and register_block_type_from_metadata. The block should have InspectorControls for color/layout settings, a dynamic render_callback in PHP, and save.js that returns null (server-side rendered). Include block.json attributes schema."

WOOCOMMERCE

"Add a WooCommerce extension that: adds a custom checkout field, validates it on woocommerce_checkout_process, saves it to order meta via woocommerce_checkout_update_order_meta, displays it in the admin order view, and includes it in order confirmation emails."

SECURITY

"Audit this WordPress plugin code for security issues: check for SQL injection ($wpdb->prepare usage), XSS (esc_html, esc_attr, esc_url), CSRF (wp_nonce_field + wp_verify_nonce), capability checks (current_user_can), and direct file access prevention. Fix every issue found."

CRON & BACKGROUND

"Create a WordPress cron job using wp_schedule_event that runs hourly, fetches data from an external API with error handling and a transient cache (set for 50 minutes to avoid thundering herd), and updates custom post meta. Add a manual trigger via admin_action_ hook."

PHP 8.x Modern Features Prompts

ENUMS

"Refactor these string constants into a PHP 8.1 backed enum: add a label() method, implement a fromLabel() static factory, add an interface for billable statuses, and ensure Doctrine/Eloquent can serialize/deserialize the enum. Keep all existing comparisons working."

READONLY

"Refactor these DTO classes to use PHP 8.2 readonly classes: constructor promotion for all properties, a static fromArray() factory, a with() method that returns a modified clone, and JSON serialization via JsonSerializable. Write tests to confirm immutability."

FIBERS

"Show me how to use PHP 8.1 Fibers to implement a simple cooperative task scheduler that processes multiple I/O-bound operations without threads. Demonstrate with three concurrent HTTP requests using Fiber::suspend() and a main loop that drives each fiber."

MATCH & PATTERNS

"Replace all switch statements in this file with match expressions. Add exhaustiveness — if not all cases are covered, throw an UnhandledMatchError. Where the matched value is a class hierarchy, use match(true) with instanceof checks. Document where you had to add a default arm and why."

INTERSECTION TYPES

"Refactor this service to use intersection types for parameters that must implement both Countable and Iterator. Add union types to return values that can be null on failure. Enable strict_types=1 and fix any type errors that emerge. Run PHPStan at level 8 and fix remaining issues."

Composer & Tooling Prompts

COMPOSER

"Set up a PHP package skeleton: composer.json with autoloading (PSR-4), dev dependencies for PHPUnit + PHPStan + PHP-CS-Fixer, a Makefile with test/analyse/fix targets, GitHub Actions CI that runs on PHP 8.1, 8.2, 8.3 matrix, and a .gitattributes to exclude dev files from the dist."

PHPSTAN

"Run PHPStan at level 8 on this codebase and fix all errors. Prioritize: missing return types, mixed type violations, dead code, and null safety issues. Where the true type is unknowable (e.g., dynamic array shapes), add @phpstan-type docblocks with a comment explaining why. Do not use @suppress without justification."

PEST PHP

"Convert this PHPUnit test file to Pest PHP: use it() / describe() / test() conventions, expect() assertions instead of $this->assert*, dataset() for data providers, and beforeEach() for setup. Keep all existing test coverage but make the tests read like specifications."

DOCKER

"Create a Docker Compose setup for this Laravel app: PHP 8.3-fpm image with required extensions (pdo_mysql, redis, gd, intl), Nginx, MySQL 8, Redis, and a Mailhog container for email testing. Include a Dockerfile with multi-stage build, .dockerignore, and health checks for all services."

PHP Feature Support Table

Capability Supported Notes
Laravel 11 (Artisan, Eloquent, Blade) ✓ Full Service container, facades, middleware, jobs, events
Symfony 7 (Doctrine, Messenger, Security) ✓ Full DI attributes, API Platform, Forms, Validator
WordPress / WooCommerce ✓ Full Hooks, CPT, REST API, Gutenberg blocks, WC extensions
PHP 8.3 features ✓ Full Enums, fibers, readonly classes, typed class constants
PHPUnit 10+ / Pest PHP ✓ Full Data providers (#[DataProvider]), Mockery, assertions
Composer packages & PSR standards ✓ Full PSR-4 autoloading, PSR-7/15/17 HTTP, PSR-3 logging
PHPStan / Psalm static analysis ✓ Full Understands generics, conditional types, @phpstan-type
PDO / raw SQL ✓ Full Prepared statements, transactions, named parameters

Performance & Optimization Prompts

N+1 FIX

"Profile this Eloquent code with Laravel Debugbar and fix every N+1 query. Use with() for eager loading, withCount() for aggregates, and load() for conditional loading. Show the before/after query count and explain each fix."

CACHING

"Add Redis caching to this service: cache the result of expensive database queries using Cache::remember(), tag the cache entries so they can be invalidated by model (Cache::tags()), and add cache warming via an Artisan command. Document the TTL reasoning."

CHUNKING

"This script loads 100K records into memory and crashes. Rewrite it using Eloquent's chunk() or lazy() cursor to process in batches of 1000, add a memory_get_peak_usage() progress log every 10 batches, and make it resumable via a checkpoint in Redis."

OPCACHE

"Audit this PHP deployment for OPcache configuration: verify opcache.validate_timestamps=0 in production, opcache.memory_consumption is sized correctly for the codebase, and preloading is configured via opcache.preload. Generate an optimized php.ini snippet with comments."

Security Prompts

SQL INJECTION

"Audit this entire codebase for SQL injection vulnerabilities: find raw string interpolation in queries, ensure all $wpdb calls use prepare(), verify PDO uses named parameters everywhere. Generate a report with file:line references and a fixed version of each vulnerable snippet."

XSS

"Review every echo and print statement in this PHP application. Add esc_html() / htmlspecialchars() to all user-controlled output. For URLs, use esc_url(). For JavaScript contexts, use wp_json_encode() or json_encode with JSON_HEX_TAG. List every change made."

CSRF

"Add CSRF protection to all state-changing POST endpoints in this application. For Laravel, verify VerifyCsrfToken middleware is active and forms include @csrf. For vanilla PHP, implement a token stored in the session and verified on submit. Write tests that confirm requests without tokens are rejected."

Frequently Asked Questions

Does Claude Code understand Laravel and Eloquent ORM?

Yes — Claude Code has deep knowledge of Laravel's architecture including Eloquent ORM, the service container and dependency injection, facades, middleware, route model binding, policies and gates, jobs and queues, events/listeners, and the full Artisan command ecosystem. It writes Eloquent queries using scopes, eager loading (with/withCount to avoid N+1), query builder fluent syntax, and correctly uses firstOrCreate, updateOrCreate, and upsert for atomic operations.

For migrations, it generates reversible Up/Down methods and flags destructive changes. It also understands the Eloquent casting system, accessor/mutator patterns, model observers, and factory patterns for testing.

How does Claude Code work with Symfony?

Claude Code understands Symfony's component architecture: Doctrine ORM, the Symfony DI container with autowiring and autoconfiguration, Event Dispatcher, Messenger (command bus, event bus), Security, Form component, Validator, Serializer, and API Platform.

It writes services with #[Autowire] and #[AsEventListener] attributes, creates Doctrine entities with proper annotations/attributes, writes DQL and QueryBuilder queries, and configures services.yaml correctly. It distinguishes between Symfony and Laravel patterns and never mixes them up.

Can Claude Code help with WordPress plugin and theme development?

Yes. Claude Code understands WordPress hooks (add_action, add_filter), custom post types, taxonomies, meta boxes, the WP REST API, WooCommerce hooks, and block development with block.json and register_block_type.

It correctly uses $wpdb with prepared statements to prevent SQL injection, sanitizes user input with sanitize_text_field/absint/esc_html, checks nonces with wp_verify_nonce, and follows security best practices. It also understands the difference between classic themes (functions.php, template parts) and Full Site Editing (theme.json, block templates).

Does Claude Code understand PHP 8.x features like enums, fibers, and readonly properties?

Yes. Claude Code uses modern PHP 8.x features correctly: backed enums (string/int) with cases, methods, and interface implementation; readonly properties and readonly classes for immutable value objects; named arguments for clarity; union types (int|string) and intersection types; nullsafe operator (?->) chains; match expressions; first-class callable syntax; and PHP 8.1+ fibers.

It recommends the appropriate feature for each use case and can upgrade legacy PHP 5/7 codebases to PHP 8.x, explaining each migration step.

How does Claude Code handle PHPUnit and Pest testing?

Claude Code writes PHPUnit tests with proper data providers (#[DataProvider] in PHPUnit 10+), mocks using createMock/getMockBuilder or Mockery, and assertion chains. It understands the difference between unit tests (isolated, no I/O), integration tests (real database via database transactions), and feature tests (full HTTP stack in Laravel/Symfony).

For Pest PHP, it uses the fluent expect() API, describe() blocks, beforeEach(), and datasets. It avoids test pollution between cases and writes descriptive names that document intent.

How do I set up CLAUDE.md for a PHP project?

A good CLAUDE.md for PHP projects should include: the PHP version and framework version; the testing command (php artisan test or ./vendor/bin/phpunit); the coding standard (PSR-12 via PHP-CS-Fixer or Laravel Pint); static analysis tool and level (PHPStan level 8 or Psalm); the local dev setup (Sail, Valet, or Docker); and key architectural decisions (service layer pattern, repository pattern, CQRS etc.).

Also list which directories are auto-generated and should not be edited: vendor/, storage/, bootstrap/cache/, public/build/ (Vite output). This prevents Claude from editing files that would be overwritten on the next build.

Can Claude Code generate Laravel API resources and controllers?

Yes. Claude Code generates complete Laravel API resources: JsonResource and ResourceCollection classes with conditional includes (whenLoaded, when, mergeWhen), Form Request validation classes with authorize and rules methods, API controllers following the single-responsibility invokable pattern or resourceful controllers, and route definitions with sanctum auth middleware.

It also writes OpenAPI docblock annotations compatible with L5-Swagger and understands the difference between API resources (for JSON output) and Blade views (for server-side HTML).

Related Guides

⚡ Using Claude Code? 30 power prompts that 2× your output · £5 £3 first 10Get PDF £3 →