Данное исчерпывающее руководство предоставляет оптимизированные промты для высококачественной разработки на PHP 8.3, основанные на анализе современных подходов к промт-инжинирингу и лучших практик профессиональной разработки.
- 1. Основы промтинга для PHP разработки
- 2. Промты для разработки нового PHP кода
- 2.1. Базовый промт для генерации кода уровня Senior (ОПТИМИЗИРОВАННЫЙ)
- 2.2. Промт для API разработки (REST/GraphQL)
- 2.3. Промт для Frontend интеграции (AJAX, JSON)
- 2.4. Промт для Backend логики (бизнес-логика, сервисы)
- 2.5. Промт для создания классов и интерфейсов
- 2.6. Промт для работы с формами и валидацией
- 3. Промты для доработки и рефакторинга PHP кода
- 4. Промты для проектирования баз данных
- 5. Специализированные промты для PHP экосистемы
- 6. Продвинутые техники промтинга
- 7. Безопасность и качество кода
- 8. Интеграция и автоматизация
- Заключение
- Ссылки по теме

1. Основы промтинга для PHP разработки
1.1. Введение в промт-инжиниринг для кода
Промт-инжиниринг для генерации кода требует понимания того, как LLM обрабатывают технические инструкции. Исследования показывают, что четко структурированные промты с конкретными требованиями дают значительно лучшие результаты, чем общие описания. Эффективный промт должен содержать роль, контекст, задачу и ожидаемый результат.
1.2. Особенности работы с LLM для генерации PHP кода
LLM имеют тенденцию к генерации «средних» решений, поэтому для получения кода уровня Senior необходимо явно указывать продвинутые паттерны и принципы. PHP как язык требует особого внимания к типизации, безопасности и современным возможностям языка.
1.3. Структура эффективного промта
Оптимальная структура промта включает:
- Роль и экспертизу (кто выполняет задачу)
- Контекст и ограничения
- Конкретную задачу
- Технические требования
- Формат вывода
- Критерии качества
1.4. Контекст и специфичность в промтах
Предоставление детального контекста о существующей кодовой базе, архитектурных паттернах и бизнес-требованиях критически важно для генерации релевантного кода. Используйте @references для указания на конкретные файлы или функции.
1.5. Chain-of-Thought для сложной логики
Для сложных алгоритмов и бизнес-логики применяйте пошаговое рассуждение, инструктируя LLM разбить задачу на логические этапы.
2. Промты для разработки нового PHP кода
2.1. Базовый промт для генерации кода уровня Senior (ОПТИМИЗИРОВАННЫЙ)
/**
* Code developed by AI Assistant under the supervision of Mikhail Deynekin (mid1977@gmail.com)
* Website: https://deynekin.com
* Date: 2025-10-23
* PHP Version: 8.3
*/
ROLE: Senior PHP Developer (20+ years experience)
TECHNICAL STACK:
- PHP 8.3 with strict typing
- PSR-12 coding standards
- Tab indentation (\t)
PRIORITY REQUIREMENTS (in order):
1. SECURITY: Prevent SQL injection, XSS, CSRF; no hardcoded secrets
2. CORRECTNESS: Zero logical/syntax errors, proper error handling
3. PERFORMANCE: Optimal algorithms, minimal memory usage
4. MAINTAINABILITY: SOLID principles, DRY, clear naming
PHP 8.3 FEATURES TO LEVERAGE:
- Use readonly properties for immutable data
- Apply typed enums for constants
- Implement match expressions over switch
- Use constructor property promotion
- Add typed class constants
ARCHITECTURE DECISIONS:
- Choose appropriate pattern (MVC/Repository/Service) based on context
- Create interfaces for dependency injection points
- Implement proper exception handling with try-catch
- Use prepared statements for all database queries
OUTPUT FORMAT:
- Complete, production-ready code
- English PHPDoc comments for public methods only
- Include type hints for all parameters and returns
- One class per file with matching namespace
QUALITY VERIFICATION:
- Each class/method has single responsibility
- No code duplication
- All inputs validated and sanitized
- Extensible without modification (Open/Closed)2.2. Промт для API разработки (REST/GraphQL)
TASK: PHP 8.3 REST API Development
ROLE: Senior API Architect
REQUIREMENTS:
- RESTful design with proper HTTP status codes
- JSON responses with consistent structure
- Request validation with custom rules
- Rate limiting and authentication
- OpenAPI 3.0 documentation structure
SECURITY FOCUS:
- JWT token validation
- Input sanitization for all endpoints
- CORS configuration
- Request size limits
STRUCTURE:
- Controller → Service → Repository pattern
- Custom Request classes for validation
- Resource transformers for responses
- Middleware for cross-cutting concerns
GENERATE:
1. Controller with CRUD operations
2. Request validation classes
3. Response resource transformers
4. Service layer with business logic
5. Basic middleware setup2.3. Промт для Frontend интеграции (AJAX, JSON)
TASK: PHP Frontend Integration
CONTEXT: Server-side processing for AJAX requests
REQUIREMENTS:
- JSON API endpoints for JavaScript consumption
- Form handling with CSRF protection
- File upload processing
- Real-time data updates
- Error handling for AJAX responses
RESPONSE FORMAT:
{
"success": boolean,
"data": object|array,
"message": string,
"errors": object
}
SECURITY:
- CSRF token validation
- File type validation
- XSS prevention in responses
- Rate limiting for AJAX endpoints
GENERATE: Complete AJAX handler with validation and response formatting2.4. Промт для Backend логики (бизнес-логика, сервисы)
TASK: Business Logic Service Development
ROLE: Senior Backend Developer
ARCHITECTURE:
- Service classes with single responsibility
- Dependency injection for external services
- Event-driven patterns where appropriate
- Command/Query separation
PATTERNS TO USE:
- Strategy pattern for varying algorithms
- Factory pattern for object creation
- Observer pattern for notifications
- Repository pattern for data access
ERROR HANDLING:
- Custom exceptions for business rules
- Logging for audit trails
- Graceful degradation
- Transaction management
GENERATE: Service class with complete business logic implementation2.5. Промт для создания классов и интерфейсов
TASK: PHP 8.3 Class/Interface Design
PRINCIPLES:
- Interface Segregation: specific interfaces over general ones
- Dependency Inversion: depend on abstractions
- Constructor property promotion where appropriate
- Readonly properties for immutable data
FEATURES:
- Typed enums for state management
- Named constructors for clarity
- Fluent interfaces where beneficial
- Proper inheritance hierarchies
DOCUMENTATION:
- PHPDoc with @param, @return, @throws
- Interface contracts clearly defined
- Usage examples in comments
GENERATE: Complete class hierarchy with interfaces and implementations2.6. Промт для работы с формами и валидацией
TASK: Form Processing with Validation
REQUIREMENTS:
- Server-side validation rules
- CSRF protection
- File upload handling
- Multi-step form support
- Localized error messages
VALIDATION RULES:
- Type checking (string, int, email, etc.)
- Length constraints
- Custom business rules
- Sanitization after validation
SECURITY:
- Input sanitization
- File type validation
- Size limits
- Path traversal prevention
GENERATE: Complete form processing class with validation and security measures3. Промты для доработки и рефакторинга PHP кода
3.1. Промт для рефакторинга существующего кода (ОПТИМИЗИРОВАННЫЙ)
/**
* Code refactored by AI Assistant under the supervision of Mikhail Deynekin (mid1977@gmail.com)
* Website: https://deynekin.com
* Refactoring Date: 2025-10-23
*/
ROLE: Senior PHP Refactoring Specialist
TASK: Refactor existing PHP code to modern standards
ANALYZE FIRST:
1. Identify code smells and anti-patterns
2. Locate security vulnerabilities
3. Find performance bottlenecks
4. Assess SOLID principle violations
REFACTORING PRIORITIES:
1. SECURITY: Fix all vulnerabilities immediately
2. CORRECTNESS: Resolve logical errors and bugs
3. ARCHITECTURE: Apply SOLID principles
4. PERFORMANCE: Optimize algorithms and queries
5. MAINTAINABILITY: Improve readability and structure
MODERNIZATION:
- Upgrade to PHP 8.3 features where beneficial
- Add strict typing declarations
- Implement proper error handling
- Apply PSR-12 coding standards
OUTPUT:
- Refactored code with explanations
- List of changes made with line numbers
- Security improvements summary
- Performance optimization notes
PRESERVE:
- Existing functionality and behavior
- Public API contracts
- Database schema compatibility3.2. Промт для оптимизации производительности
TASK: PHP Performance Optimization
FOCUS AREAS:
- Algorithm complexity (Big-O optimization)
- Database query optimization
- Memory usage reduction
- Caching implementation
- Lazy loading patterns
ANALYSIS:
- Profile current performance bottlenecks
- Identify N+1 query problems
- Find memory leaks
- Locate inefficient loops
OPTIMIZATIONS:
- Use appropriate data structures
- Implement query batching
- Add strategic caching
- Optimize file I/O operations
GENERATE: Performance-optimized code with benchmarking comments3.3. Промт для исправления уязвимостей безопасности
TASK: Security Vulnerability Remediation
SECURITY AUDIT FOCUS:
- SQL injection prevention
- XSS attack vectors
- CSRF protection
- Input validation gaps
- Authentication/authorization flaws
FIXES TO IMPLEMENT:
- Prepared statements for all database queries
- Input sanitization and validation
- Output encoding for HTML context
- Secure session management
- Password hashing best practices
GENERATE: Secure code with detailed security improvement explanations3.4. Промт для применения SOLID принципов
TASK: SOLID Principles Implementation
ANALYZE VIOLATIONS:
- Single Responsibility: classes doing too much
- Open/Closed: modifications instead of extensions
- Liskov Substitution: improper inheritance
- Interface Segregation: fat interfaces
- Dependency Inversion: concrete dependencies
REFACTORING APPROACH:
- Extract methods and classes
- Create proper abstractions
- Implement dependency injection
- Design focused interfaces
- Use composition over inheritance
GENERATE: SOLID-compliant code with principle explanations3.5. Промт для устранения дублирования кода (DRY)
TASK: Code Duplication Elimination
IDENTIFY PATTERNS:
- Repeated logic blocks
- Similar method implementations
- Duplicate validation rules
- Redundant configuration
DRY STRATEGIES:
- Extract common functionality to methods
- Create reusable utility classes
- Implement inheritance hierarchies
- Use traits for shared behavior
- Apply template method pattern
GENERATE: DRY-compliant code with extracted reusable components3.6. Промт для приведения к PSR-12 стандартам
TASK: PSR-12 Compliance Update
FORMATTING REQUIREMENTS:
- Tab indentation (\t)
- Opening braces on new lines for classes/methods
- Proper spacing around operators
- Line length limits (120 chars max)
- Consistent naming conventions
STRUCTURE:
- declare(strict_types=1) at file top
- Proper namespace declarations
- Organized use statements
- Method visibility declarations
GENERATE: PSR-12 compliant code with formatting explanations4. Промты для проектирования баз данных
4.1. Промт для создания схемы базы данных
TASK: Database Schema Design
REQUIREMENTS ANALYSIS:
- Business entities and relationships
- Data volume estimates
- Query patterns and frequency
- Performance requirements
- Scalability considerations
DESIGN PRINCIPLES:
- Third Normal Form (3NF) minimum
- Appropriate indexing strategy
- Foreign key constraints
- Data type optimization
- Partitioning considerations
GENERATE:
- CREATE TABLE statements
- Index definitions
- Constraint declarations
- Relationship documentation
- Migration scripts4.2. Промт для нормализации таблиц
TASK: Database Normalization
ANALYZE CURRENT STRUCTURE:
- Identify redundant data
- Find partial dependencies
- Locate transitive dependencies
- Assess update anomalies
NORMALIZATION PROCESS:
- First Normal Form (1NF): atomic values
- Second Normal Form (2NF): full dependencies
- Third Normal Form (3NF): no transitive dependencies
- Consider denormalization for performance
GENERATE: Normalized schema with migration path4.3. Промт для создания миграций
TASK: Database Migration Development
MIGRATION REQUIREMENTS:
- Backward compatibility
- Data preservation
- Rollback capability
- Performance during migration
- Zero-downtime considerations
STRUCTURE:
- Up/down methods
- Schema changes
- Data transformations
- Index management
- Constraint modifications
GENERATE: Complete migration with rollback strategy4.4. Промт для оптимизации запросов
TASK: SQL Query Optimization
PERFORMANCE ANALYSIS:
- Query execution plans
- Index usage patterns
- Join optimization
- Subquery vs JOIN performance
- Pagination efficiency
OPTIMIZATION TECHNIQUES:
- Proper indexing strategy
- Query restructuring
- Temporary table usage
- Batch processing
- Caching strategies
GENERATE: Optimized queries with performance explanations4.5. Промт для создания индексов
TASK: Database Index Strategy
INDEX ANALYSIS:
- Query patterns identification
- Column selectivity analysis
- Composite index opportunities
- Covering index benefits
- Write performance impact
INDEX TYPES:
- Primary/unique indexes
- Composite indexes
- Partial indexes
- Full-text indexes
- Spatial indexes (if applicable)
GENERATE: Complete indexing strategy with CREATE INDEX statements4.6. Промт для работы с ORM (Eloquent, Doctrine)
TASK: ORM Integration and Optimization
ORM PATTERNS:
- Entity relationship mapping
- Lazy/eager loading strategies
- Query builder optimization
- Migration handling
- Seeding and factories
PERFORMANCE CONSIDERATIONS:
- N+1 query prevention
- Batch operations
- Connection pooling
- Cache integration
- Query optimization
GENERATE: Complete ORM setup with optimized queries and relationships5. Специализированные промты для PHP экосистемы
5.1. Промты для WordPress разработки
TASK: WordPress Plugin/Theme Development
WORDPRESS STANDARDS:
- WordPress Coding Standards
- Plugin/theme architecture
- Hook and filter system
- Security best practices (nonces, sanitization)
- Internationalization (i18n)
FEATURES:
- Custom post types and fields
- Database table creation
- Admin interface integration
- AJAX handling
- Frontend optimization
GENERATE: WordPress-compliant code with proper hook integration5.2. Промты для Laravel проектов
TASK: Laravel Application Development
LARAVEL PATTERNS:
- MVC architecture
- Eloquent ORM usage
- Service providers
- Middleware implementation
- Artisan commands
FEATURES:
- RESTful resource controllers
- Form request validation
- Event/listener system
- Queue job processing
- Cache optimization
GENERATE: Laravel best-practice implementation with proper framework integration5.3. Промты для Symfony приложений
TASK: Symfony Component Development
SYMFONY ARCHITECTURE:
- Bundle structure
- Dependency injection container
- Service configuration
- Event dispatcher
- Console commands
FEATURES:
- Form handling
- Security component
- Doctrine integration
- Twig templating
- HTTP kernel customization
GENERATE: Symfony-compliant code with proper component usage5.4. Промты для тестирования (PHPUnit)
TASK: PHPUnit Test Development
TESTING STRATEGY:
- Unit tests for business logic
- Integration tests for components
- Functional tests for workflows
- Mock objects for dependencies
- Test data fixtures
TEST STRUCTURE:
- Arrange-Act-Assert pattern
- Test case organization
- Setup/teardown methods
- Data providers
- Exception testing
GENERATE: Comprehensive test suite with proper coverage5.5. Промты для создания документации
TASK: PHP Code Documentation
DOCUMENTATION TYPES:
- PHPDoc comments
- API documentation
- Architecture documentation
- Setup instructions
- Usage examples
TOOLS INTEGRATION:
- phpDocumentor
- OpenAPI/Swagger
- Markdown formatting
- Code examples
- Changelog maintenance
GENERATE: Complete documentation with examples and setup instructions5.6. Промты для командной строки (CLI)
TASK: PHP CLI Application Development
CLI FEATURES:
- Command-line argument parsing
- Interactive prompts
- Progress indicators
- Output formatting
- Error handling
ARCHITECTURE:
- Command pattern implementation
- Input/output abstraction
- Configuration management
- Logging integration
- Signal handling
GENERATE: Complete CLI application with user-friendly interface6. Продвинутые техники промтинга
6.1. Multi-step промтинг (цепочки промтов)
Используйте последовательность специализированных промтов для сложных задач:
Шаг 1: Анализ
Analyze this PHP code for architectural issues, security vulnerabilities, and performance bottlenecks. Provide a detailed assessment without making changes.Шаг 2: Планирование
Based on the analysis, create a refactoring plan with prioritized improvements and estimated impact.Шаг 3: Реализация
Implement the highest priority improvements from the refactoring plan, ensuring backward compatibility.6.2. Meta-prompting для саморефлексии кода
You are an expert code reviewer. Analyze the PHP code I provide and then create an improved version of this prompt that would generate better PHP code for similar tasks. Consider specificity, clarity, and technical accuracy.6.3. Few-shot промтинг с примерами
Включайте 2-3 качественных примера кода в промт для демонстрации ожидаемого стиля и качества.
6.4. Промты с ролевым контекстом
You are a Senior PHP Architect reviewing code for a fintech application handling sensitive financial data. Security and performance are critical. Apply banking-grade security standards and optimize for high-volume transactions.6.5. Итеративное улучшение через обратную связь
Review the generated code and identify 3 potential improvements. Then implement these improvements and explain the reasoning behind each change.6.6. Промты для архитектурных решений
TASK: Architecture Decision
CONTEXT: [Describe business requirements and constraints]
OPTIONS TO EVALUATE:
- Monolithic vs Microservices
- Database choice (MySQL/PostgreSQL/NoSQL)
- Caching strategy (Redis/Memcached)
- Message queues (RabbitMQ/Apache Kafka)
DECISION CRITERIA:
- Scalability requirements
- Team expertise
- Maintenance overhead
- Performance requirements
- Budget constraints
GENERATE: Architecture recommendation with trade-off analysis7. Безопасность и качество кода
7.1. Промты для анализа безопасности
TASK: Security Code Audit
SECURITY CHECKLIST:
- SQL injection vulnerabilities
- XSS attack vectors
- CSRF protection
- Authentication bypass
- Authorization flaws
- Input validation gaps
- Output encoding issues
- Session management
- Password handling
- File inclusion vulnerabilities
ANALYSIS OUTPUT:
- Vulnerability severity ranking
- Exploitation scenarios
- Remediation recommendations
- Security best practice violations
GENERATE: Comprehensive security audit report with fixes7.2. Промты для code review
TASK: Senior-Level Code Review
REVIEW CRITERIA:
- Code correctness and logic
- Security implications
- Performance considerations
- Maintainability factors
- Adherence to standards
- Architecture alignment
- Test coverage adequacy
FEEDBACK FORMAT:
- Must-fix issues (blocking)
- Should-fix improvements
- Nice-to-have suggestions
- Positive reinforcement
GENERATE: Detailed code review with actionable feedback7.3. Промты для статического анализа
TASK: Static Code Analysis
ANALYSIS TOOLS SIMULATION:
- PHPStan/Psalm-level type checking
- PHPCS standard compliance
- PHPMD complexity analysis
- Security vulnerability scanning
METRICS TO REPORT:
- Cyclomatic complexity
- Code coverage gaps
- Type safety issues
- Standard violations
- Dead code detection
GENERATE: Static analysis report with improvement recommendations7.4. Промты для обнаружения anti-patterns
TASK: Anti-Pattern Detection
COMMON PHP ANTI-PATTERNS:
- God objects (classes doing too much)
- Spaghetti code (poor structure)
- Magic numbers and strings
- Global state dependencies
- Tight coupling
- Pyramid of doom (nested conditionals)
DETECTION AND FIXES:
- Identify anti-pattern occurrences
- Explain why it's problematic
- Provide refactored solution
- Suggest prevention strategies
GENERATE: Anti-pattern analysis with refactored alternatives7.5. Промты для соответствия стандартам
TASK: Standards Compliance Check
STANDARDS TO VERIFY:
- PSR-1: Basic Coding Standard
- PSR-2/PSR-12: Coding Style Guide
- PSR-4: Autoloading Standard
- PSR-7: HTTP Message Interface
- PSR-11: Container Interface
COMPLIANCE ASSESSMENT:
- Standard violations identification
- Severity level assignment
- Automatic fix suggestions
- Manual review requirements
GENERATE: Standards compliance report with corrected code7.6. Промты для аудита зависимостей
TASK: Dependency Security Audit
AUDIT SCOPE:
- Composer.json analysis
- Vulnerable package identification
- Outdated dependencies
- License compatibility
- Performance impact assessment
SECURITY CONSIDERATIONS:
- Known CVE vulnerabilities
- Unmaintained packages
- Supply chain risks
- Update recommendations
GENERATE: Dependency audit report with update roadmap8. Интеграция и автоматизация
8.1. Промты для CI/CD интеграции
TASK: CI/CD Pipeline Configuration
PIPELINE STAGES:
- Code quality checks (PHPCS, PHPStan)
- Security scanning (Psalm, PHP Security Checker)
- Automated testing (PHPUnit)
- Dependency validation
- Deployment automation
TOOLS INTEGRATION:
- GitHub Actions/GitLab CI
- Quality gates configuration
- Artifact management
- Environment-specific deployments
GENERATE: Complete CI/CD configuration with quality gates8.2. Промты для Docker конфигурации
TASK: PHP Docker Configuration
CONTAINER REQUIREMENTS:
- PHP 8.3 with required extensions
- Composer for dependency management
- Development vs production variants
- Multi-stage build optimization
- Security hardening
ORCHESTRATION:
- Docker Compose setup
- Service dependencies
- Volume management
- Network configuration
- Environment variables
GENERATE: Production-ready Docker configuration8.3. Промты для развертывания
TASK: Deployment Strategy
DEPLOYMENT TYPES:
- Rolling deployment
- Blue-green deployment
- Canary releases
- Zero-downtime deployment
CONSIDERATIONS:
- Database migrations
- Cache warming
- Health checks
- Rollback procedures
- Monitoring integration
GENERATE: Deployment scripts with rollback capability8.4. Промты для мониторинга и логирования
TASK: Monitoring and Logging Setup
MONITORING ASPECTS:
- Application performance metrics
- Error rates and patterns
- Resource utilization
- Business metrics tracking
- Alert configuration
LOGGING STRATEGY:
- Structured logging (JSON)
- Log levels and categories
- Sensitive data handling
- Log aggregation
- Retention policies
GENERATE: Complete monitoring and logging implementation8.5. Промты для создания API документации
TASK: API Documentation Generation
DOCUMENTATION STANDARDS:
- OpenAPI 3.0 specification
- Request/response examples
- Authentication details
- Error code documentation
- Rate limiting information
TOOLS INTEGRATION:
- Swagger/OpenAPI generators
- Postman collection export
- Interactive documentation
- Version management
GENERATE: Complete API documentation with examples8.6. Промты для интеграции с внешними сервисами
TASK: External Service Integration
INTEGRATION PATTERNS:
- REST API consumption
- Webhook handling
- Authentication flows (OAuth2, JWT)
- Rate limiting compliance
- Error handling and retries
RELIABILITY MEASURES:
- Circuit breaker pattern
- Timeout configuration
- Fallback strategies
- Monitoring and alerting
GENERATE: Robust external service integration with error handlingЗаключение
Это руководство предоставляет полный набор оптимизированных промтов для профессиональной PHP разработки уровня Senior. Каждый промт спроектирован с учетом современных лучших практик промт-инжиниринга и требований высококачественной разработки программного обеспечения.
Ключевые принципы эффективного промтинга для PHP:
- Специфичность: Четкие, конкретные инструкции превосходят общие описания
- Контекст: Предоставление релевантной информации о проекте и требованиях
- Структурированность: Логическое разделение требований по приоритетам
- Итеративность: Использование цепочек промтов для сложных задач
- Качество: Явное указание стандартов и принципов профессиональной разработки
Применение данных промтов позволит значительно повысить качество генерируемого PHP кода, обеспечить соответствие современным стандартам разработки и создать maintainable, secure и performant приложения.
⁂