pbweb/xhprof
Laravel-friendly integration for XHProf profiling. Collect and store performance data (CPU, memory, call graphs) for your PHP requests, making it easier to analyze slow code paths and regressions during development or troubleshooting.
Installation
composer require pbweb/xhprof
Ensure ext-xhprof is enabled in your PHP environment (php -m | grep xhprof).
Basic Initialization
Add to bootstrap/app.php (Laravel 9+):
$app->register(\PBWeb\XHProf\XHProfServiceProvider::class);
Or manually in a service provider:
use PBWeb\XHProf\XHProf;
XHProf::enable();
First Use Case Profile a route or controller method:
use PBWeb\XHProf\XHProf;
Route::get('/profile', function () {
XHProf::start('route_example');
// Your logic here
$data = XHProf::stop();
// Store/process $data (see Implementation Patterns)
});
Middleware for Automatic Profiling Create middleware to profile all requests:
namespace App\Http\Middleware;
use PBWeb\XHProf\XHProf;
use Closure;
class ProfileRequests
{
public function handle($request, Closure $next)
{
XHProf::start('request_' . $request->path());
$response = $next($request);
$data = XHProf::stop();
// Log or store $data (e.g., to a database or file)
return $response;
}
}
Register in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\ProfileRequests::class,
];
Command-Line Profiling Profile Artisan commands:
use PBWeb\XHProf\XHProf;
use Illuminate\Console\Command;
class OptimizeCommand extends Command
{
protected $signature = 'optimize:assets';
public function handle()
{
XHProf::start('optimize_assets');
// Command logic
$data = XHProf::stop();
$this->info('Profiling data saved.');
}
}
Database Storage
Store results in a table (e.g., profiling_results):
use PBWeb\XHProf\XHProf;
use Illuminate\Support\Facades\DB;
XHProf::start('db_query');
DB::table('users')->get();
$data = XHProf::stop();
DB::table('profiling_results')->insert([
'name' => 'db_query',
'data' => json_encode($data),
'created_at' => now(),
]);
Visualization
Use the built-in xhprof_html utility or integrate with tools like:
Performance Overhead XHProf adds ~3-10% overhead to execution time. Disable in production:
if (app()->environment('production')) {
XHProf::disable();
}
Memory Leaks Stop profiling explicitly to avoid memory buildup:
XHProf::stop(); // Always call this!
Thread Safety
XHProf is not thread-safe. Avoid concurrent profiling in multi-threaded environments (e.g., Laravel Queues with ignore_failure workers).
PHP Version Compatibility
Verify Extension
Confirm xhprof is loaded:
php -m | grep xhprof
If missing, install via PECL:
pecl install xhprof
Check for Errors Wrap profiling in a try-catch:
try {
XHProf::start('test');
// Code
XHProf::stop();
} catch (\Exception $e) {
\Log::error('XHProf error: ' . $e->getMessage());
}
Corrupted Data
If $data is empty after stop(), ensure:
enable() was called before profiling.start() calls without stop().Profile Critical Paths Focus on:
DB::select()).Http::get()).Compare Baselines Profile the same code before/after optimizations to measure impact.
Exclude Vendor Code
Use XHProf::setExclude() to ignore Laravel/framework code:
XHProf::setExclude(['vendor/', 'bootstrap/']);
Custom Storage
Extend the package by overriding the stop() method:
XHProf::extendStop(function ($data) {
// Custom logic (e.g., upload to S3)
return $data;
});
CI/CD Integration Add profiling to your test suite:
// In a test case
public function testPerformance()
{
XHProf::start('test_performance');
// Test logic
$data = XHProf::stop();
$this->assertLessThan(100, $data['wall_time']); // Example assertion
}
How can I help you explore Laravel packages today?