.claude/skills/php-optimization-engineer/SKILL.md
Automatically analyzes and optimizes PHP code by identifying performance bottlenecks, memory issues, and applying fixes directly to files. Creates backups before modifications and provides rollback instructions. Use when user wants to optimize PHP code, improve performance, reduce memory usage, refactor for efficiency, profile code, or investigate deeper into performance issues. Triggers on "optimize PHP", "PHP performance", "slow PHP script", "PHP memory issue", "improve PHP code", "PHP bottleneck", "PHP refactoring", "profile PHP", "PHP profiler", "profile code", "investigate performance", "performance investigation", "debug performance", "analyze performance".
npx skillsauth add FacuM/yolo-agent php-optimization-engineerInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Automatically analyzes PHP codebases to identify performance bottlenecks, memory inefficiencies, and optimization opportunities, then applies optimizations directly to the code files with proper safety measures.
Requires docker, docker compose, and a PHP environment with necessary extensions for analysis and testing. If the PHP version installed locally is not compatible, use the provided Docker setup for a consistent environment. If no Docker environment is available, use a compatible image from Docker Hub to run the analysis and optimizations.
This skill automatically implements optimizations directly in PHP files. To ensure safety and control:
Scan for common optimization opportunities:
Performance Patterns:
new MongoDB\Client inside a loop). in loops instead of arrays + implode)count() when isset() would suffice)eval() or dynamic code executiondefine('CONFIG_VALUE', 'value') instead of $configValue = 'value', or calling getenv('CONFIG_VALUE')` repeatedly instead of defining a constant)__get, __set, __call) that can add overhead and reduce readabilitystrtotime() multiple times with the same date string)Memory Patterns:
unset() for large variablesDatabase Patterns:
Caching Patterns:
Look for:
foreach/for loops that could use array functionsfilled(), blank() and empty() that could be optimized by using isset() or direct checksLook for:
array_map/array_filter creating copies unnecessarilyLook for:
Look for:
Pre-Implementation Safety
Apply Optimizations by Priority
For Each Optimization Applied:
Post-Implementation Validation
Always Create Backups
# Automatic branch creation and backup
git checkout -b optimization-$(date +%Y%m%d-%H%M%S)
Git Integration (Recommended)
# Commit current state before optimizations
git add -A && git commit -m "Pre-optimization snapshot"
Verify File Writability
Run Tests
# PHPUnit
php vendor/bin/phpunit
# Laravel
php artisan test
# Symfony
php bin/phpunit
Note which tests failed and why, if any. There's a high likelihood that those failures are not due to the optimizations but it's important to verify.
Syntax Validation
php -l path/to/file.php
Provide Rollback Instructions
# To rollback all changes via git
git checkout <previous-branch>
For every file modified, provide:
| Category | Common Issues | Solutions | |----------|--------------|-----------| | Loops | Nested iterations, repeated operations | Use array functions, cache results | | String Operations | Concatenation in loops | Use array + implode, heredoc syntax | | Function Calls | Repeated expensive calls | Cache results, use memoization | | File I/O | Multiple file reads | Read once, cache content | | Object Creation | Unnecessary instantiation | Use static methods, singletons |
| Category | Common Issues | Solutions | |----------|--------------|-----------| | Arrays | Large copies, unnecessary duplication | Use references, generators | | Database Results | Fetching all rows | Use unbuffered queries, pagination | | Variables | Large objects in memory | Unset after use, use weak references | | Strings | Large string operations | Use streams, process in chunks |
| Category | Common Issues | Solutions | |----------|--------------|-----------| | Queries | N+1 problems, SELECT * | Use JOINs, specify columns | | Indexes | Missing or inefficient | Add appropriate indexes | | Connections | New connection per query | Use connection pooling | | Transactions | Missing for multiple ops | Wrap in transactions |
| Category | Common Issues | Solutions | |----------|--------------|-----------| | Data | Repeated expensive queries | Implement query caching | | Computation | Same calculations repeated | Use memoization patterns | | Views | Templates parsed repeatedly | Compile templates, cache output |
# PHP Optimization Report
## Summary
- Files Analyzed: [count]
- Optimizations Applied: [count]
- Critical: [count] | High: [count] | Medium: [count] | Low: [count]
- Branch Created: [branch name]
## Applied Optimizations
### Optimization #1: [Title]
**File:** `path/to/file.php:123`
**Priority:** Critical
**Category:** Performance | Memory | Database | Caching
**Original Code:**
```php
// Previous implementation
Applied Optimization:
// Optimized implementation
Change Description: [What was changed and why]
Expected Improvement: [Quantified or described benefit]
Validation:
# Command to verify the change
php -l path/to/file.php
[List of easy-to-implement optimizations that were applied, if any]
php -i | grep spx to check if SPX is available and properly configured, take note of the SPX version and configuration settings for reference in optimization decisions, especially its data directory location.SPX_ENABLED=1 SPX_REPORT=full SPX_AUTO_START=1 SPX_BUILTINS=1 SPX_METRICS=wt,ct,it,zm,mor,io,ior,iow php your_script.php to generate a comprehensive report.ls -tr1 /path/to/spx/data/directory/ | tail -n 1 to find the latest SPX report file, then analyze it to identify specific functions or lines of code that are causing performance issues or memory leaks. Use this information to apply targeted optimizations in the PHP codebase.wait on file, wait on stream, wait on socket or anything related to it (idle time), it may indicate that the script is waiting for external resources, such as file I/O, network requests, or database queries. In this case, consider optimizing those interactions by reducing the number of calls, using asynchronous processing, or implementing caching strategies to minimize wait times. Ultimately, if nothing helps, ask the user to investigate the infrastructure associated to those external resources, as the bottleneck may be outside of the PHP code itself.io, ior, iow), it may indicate that the script is performing a lot of input/output operations, such as reading/writing files or making network requests. In this case, consider optimizing those interactions by reducing the number of calls, using asynchronous processing, or implementing caching strategies to minimize I/O operations. If the I/O operations are related to database interactions, consider optimizing the database queries or connection handling to reduce the number of I/O operations required.The PHP compiler is generally very good at optimizing code, however, there may be edge cases where the optimizations applied by this skill can't cover these known edge cases. In those cases, use context clues and do a deeper research of the code, then, check if any of these specific optimizations can be applied to the codebase:
if (count($array) > 0), use if (!empty($array)) or if (isset($array[0])) to avoid counting the entire array.foreach to filter an array, use array_filter() for better performance.implode() to concatenate them all at once.strtotime() multiple times with the same date string, call it once and store the result in a variable for reuse.is_array() to check if a variable is an array, use (array) $variable === $variable to avoid the overhead of a function call, trying to cast the variable to an array and comparing it to the original variable, this can be faster than calling is_array().file_get_contents() to read a file, use fopen() and fread() for better performance, especially for large files, as it allows you to read the file in chunks instead of loading the entire file into memory at once.json_encode() and json_decode() to process JSON data, consider using a streaming JSON parser if the data is large, as it can process the data in chunks and reduce memory usage. If on PHP 8.0 or higher, consider using awesomized/simdjson-plus-php-ext (downloadable from GitHub) for significantly faster JSON processing, especially for large datasets, as it leverages SIMD instructions for parsing.Carbon, attempt to minimize the number of Carbon instances created, as they can be memory-intensive. Consider using native PHP date functions or a lightweight date library if only basic date manipulation is needed, or if the code creates many Carbon instances in a loop, try to refactor it to create fewer instances by reusing them or by using static methods when possible.kubeconfig file or the necessary credentials to access the cluster, then, use kubectl to access the logs of the relevant pods and check for any errors or performance issues that may be occurring. Check if the size of the capacity of the infrastructure is sufficient for the workload, and if there are any resource limits being hit that could be causing performance degradation. Use get events to check for any events related to the pods that may indicate issues with scheduling, resource allocation, or other problems that could be affecting performance.
## Profiling with SPX
**CRITICAL: When the user requests profiling or performance investigation, you MUST use SPX (Simple Profiling eXtension) as the profiler. Do NOT use Xdebug, Blackfire, Tideways, or any other profiler unless SPX is genuinely unavailable and all attempts to install it have failed.**
SPX is the required profiler for this skill because:
- Minimal performance overhead compared to other profilers
- Built-in web UI for analyzing results
- Detailed metrics including wall time, CPU time, idle time, memory, and I/O
- No external service dependencies
### SPX Profiling Workflow
1. **Check SPX Availability**
```bash
php -i | grep spx
If SPX is available, note the version and configuration, especially the data directory location.
If SPX is Not Available
Run SPX Profiler
# CLI profiling with comprehensive metrics
SPX_ENABLED=1 SPX_REPORT=full SPX_AUTO_START=1 SPX_BUILTINS=1 SPX_METRICS=wt,ct,it,zm,mor,io,ior,iow php your_script.php
# Web request profiling (add to URL or header)
# Add SPX_ENABLED=1&SPX_REPORT=full to query string
# Or add X-SPX-Enabled: 1 header
Analyze SPX Results
# Find the latest SPX report
ls -tr1 /path/to/spx/data/directory/ | tail -n 1
# Open the web UI (if available)
# Navigate to /spx.php in your application
Interpret SPX Metrics
wt - Wall Time: Total elapsed timect - CPU Time: Time spent executing codeit - Idle Time: Time waiting for I/O or external resourceszm - Zend Memory: Memory allocated by PHPmor - Memory Own Retained: Memory retained by functionsio, ior, iow - I/O operations (read/write)it (Idle Time): Script is waiting for external resources (file I/O, network, database). Optimize those interactions or investigate infrastructure.In Laravel, look for any calls to dd() or dump() that should be removed in production code. In Symfony, check for any dump() calls that may have been left in. In general, look for any debugging statements that may have been left in the code and remove them as part of the optimization process, these calls are generally leaking memory and should be removed in production code.
documentation
Extract frames from a YouTube video and analyze them to identify a sequence of steps. Use when user provides a YouTube URL and wants to understand the process, tutorial, or workflow shown in the video by examining its visual content frame-by-frame. Triggers on "extract steps from video", "what steps does this video show", "analyze YouTube tutorial", "screenshot a video", "figure out the steps".
testing
Use when creating new skills, editing existing skills, or verifying skills work before deployment
documentation
This skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
development
Use when you have a spec or requirements for a multi-step task, before touching code