Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Xhprof Laravel Package

laracraft-tech/laravel-xhprof

Laravel package integrating XHProf profiling into your app. Capture and review performance data for requests, analyze bottlenecks, and compare runs to optimize code, queries, and overall response time with minimal setup and overhead.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:
    composer require laracraft-tech/laravel-xhprof
    
  2. Publish configuration and migrations:
    php artisan vendor:publish --tag=xhprof-config
    php artisan vendor:publish --tag=xhprof-migrations
    php artisan migrate
    
  3. Enable XHProf in PHP:
    • Uncomment extension=xhprof.so in your php.ini.
    • Set XHPROF_SAMPLE_RATE (e.g., XHPROF_SAMPLE_RATE=100 for full profiling or 10 for sampling).

First Use Case: Profiling a Web Request

  • Append ?profile=1 to any Laravel route (e.g., http://your-app.test/api/orders?profile=1).
  • View the profile via:
    • Web route: /xhprof (default).
    • CLI command:
      php artisan xhprof:view
      
  • Expected Output: Flame graphs, call trees, and metrics for wall time, memory usage, and function-level breakdowns.

First Use Case: Profiling a CLI Command

Wrap command logic with the facade:

use LaracraftTech\Xhprof\Facades\Xhprof;

public function handle()
{
    Xhprof::start('cli-job');
    // Your logic here...
    $profile = Xhprof::stop();
    // Save or log the profile
}

Implementation Patterns

Workflow: Profiling a Slow Endpoint

  1. Identify the endpoint (e.g., /api/orders).
  2. Enable profiling:
    • Temporary: Append ?profile=1 to the URL.
    • Permanent: Add middleware to app/Http/Kernel.php:
      protected $middlewareGroups = [
          'web' => [
              \LaracraftTech\Xhprof\Http\Middleware\Profile::class,
              // Other middleware...
          ],
      ];
      
  3. Analyze results:
    • Check /xhprof for the latest profile.
    • Focus on:
      • Wall time spikes (slow queries, loops).
      • Memory peaks (large payloads, serialization).
      • Call trees for redundant function calls.
  4. Optimize and verify:
    • Fix bottlenecks (e.g., optimize queries, cache results).
    • Re-profile to confirm improvements.

Workflow: Enforcing Performance SLAs in Tests

  1. Add a test case:
    use LaracraftTech\Xhprof\Facades\Xhprof;
    use Tests\TestCase;
    
    class PerformanceTest extends TestCase
    {
        public function test_api_response_time()
        {
            Xhprof::start('api-performance-test');
            $response = $this->get('/api/orders');
            $profile = Xhprof::stop();
            $this->assertLessThan(500, $profile->getWallTime(), "API response time exceeds 500ms");
        }
    }
    
  2. Run tests:
    php artisan test --filter PerformanceTest
    
    • Fails if the SLA is violated.

Workflow: Profiling CLI Jobs and Queues

  1. Instrument the job:
    use LaracraftTech\Xhprof\Facades\Xhprof;
    
    class ProcessOrders implements ShouldQueue
    {
        public function handle()
        {
            Xhprof::start('process-orders-job');
            // Job logic...
            $profile = Xhprof::stop();
            file_put_contents(storage_path('logs/xhprof-job.log'), print_r($profile, true));
        }
    }
    
  2. Dispatch the job:
    php artisan queue:work
    
  3. Review profiles in storage/logs/xhprof-job.log or the database.

Integration Tips

  • Middleware Order: Place \LaracraftTech\Xhprof\Http\Middleware\Profile early in the middleware stack.
  • Environment Gating: Restrict profiling to local/staging in config/xhprof.php:
    'enabled' => env('APP_ENV') !== 'production',
    
  • Skip Noisy Routes: Exclude routes using skip_urls:
    'skip_urls' => [
        'health-check',
        'admin/*',
    ],
    
  • Storage Backend: For high-volume profiling, switch to file storage:
    'storage' => 'file',
    
  • Custom Storage: Implement the Storage interface for S3 or other backends.

Gotchas and Tips

Pitfalls

  1. XHProf Extension Missing:

    • Symptom: Empty profiles or xhprof_enable() errors.
    • Fix: Install the extension and set XHPROF_SAMPLE_RATE in php.ini.
    • Debug: Verify with php -m | grep xhprof.
  2. Database Storage Bloat:

    • Symptom: Slow queries due to large xhprof_runs table.
    • Fix: Prune old profiles:
      php artisan xhprof:prune --days=30
      
      Or switch to file storage.
  3. Middleware Order Issues:

    • Symptom: Incomplete wall time in profiles.
    • Fix: Move \LaracraftTech\Xhprof\Http\Middleware\Profile to the top of the middleware stack.
  4. Case Sensitivity in Skip Rules:

    • Symptom: Routes like /Health are not skipped.
    • Fix: Use exact substrings or regex.
  5. Blob Data Truncation (MySQL):

    • Symptom: Large profiles are truncated.
    • Fix: Ensure xhprof_runs uses LONGTEXT for the data column (handled in v1.0.10+ migrations).
  6. CLI Profiling Overhead:

    • Symptom: Profiling CLI jobs adds significant overhead.
    • Fix: Use sampling (XHPROF_SAMPLE_RATE=10) or profile selectively.

Debugging Tips

  • Check Profiles: Use php artisan xhprof:view to inspect the latest profile.
  • Log Profiles: Save profiles to files for later analysis:
    $profile = Xhprof::stop();
    file_put_contents(storage_path('logs/xhprof-' . now()->timestamp . '.log'), print_r($profile, true));
    
  • Compare Branches: Use git bisect with profiling to identify regressions.

Extension Points

  1. Custom Storage Backend:

    • Implement the LaracraftTech\Xhprof\Contracts\Storage interface and bind it in a service provider.
  2. Custom Middleware:

    • Extend \LaracraftTech\Xhprof\Http\Middleware\Profile to add logic (e.g., conditional profiling).
  3. Visualization:

    • Integrate with tools like Tideways or Blackfire for advanced flame graphs by exporting XHProf data.
  4. Automated Alerts:

    • Hook into the xhprof.saved event to trigger alerts for performance thresholds:
      \LaracraftTech\Xhprof\Events\ProfileSaved::class => function ($event) {
          if ($event->profile->getWallTime() > 1000) {
              // Send alert (e.g., Slack, PagerDuty)
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope