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

Integrate XHProf profiling into your Laravel app to measure request performance, capture CPU/memory metrics, and analyze call graphs. Includes middleware/collectors to enable profiling per route or environment and store runs for later review.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    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.ini (ensure extension=xhprof.so is uncommented and XHPROF_SAMPLE_RATE is set, 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).
  • Access the generated profile via /xhprof (default route) or use the CLI command:
    php artisan xhprof:view
    
  • Expected Output: A flame graph or call tree showing wall time, memory usage, and function-level breakdowns.

First Use Case: Profiling a CLI Command

Wrap your Artisan command logic with the facade:

use LaracraftTech\Xhprof\Facades\Xhprof;

public function handle()
{
    Xhprof::start('cli-job');

    // Your logic here...

    $profile = Xhprof::stop();
    // Optionally save or log the profile
}

Implementation Patterns

Workflow: Profiling a Slow Endpoint

  1. Identify the endpoint (e.g., /api/orders is slow).
  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,
          ],
      ];
      
  3. Analyze results:
    • Check /xhprof for the latest profile.
    • Look for:
      • Wall time spikes (e.g., slow queries, loops).
      • Memory peaks (e.g., large payloads, serialization).
      • Call trees to spot 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. Install PHPUnit extension (e.g., phpunit/phpunit with assertions).
  2. 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();
            $wallTime = $profile->getWallTime();
    
            $this->assertLessThan(500, $wallTime, "API response time exceeds 500ms");
        }
    }
    
  3. Run tests:
    php artisan test --filter PerformanceTest
    
    • Fails if the SLA is violated (e.g., response time > 500ms).

Workflow: Profiling CLI Jobs and Queues

  1. Instrument the job:
    use LaracraftTech\Xhprof\Facades\Xhprof;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    use Illuminate\Queue\InteractsWithQueue;
    
    class ProcessOrders implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle()
        {
            Xhprof::start('process-orders-job');
    
            // Job logic here...
    
            $profile = Xhprof::stop();
            // Log or save the profile for review
            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 database.

Integration Tips

  • Middleware Order: Ensure \LaracraftTech\Xhprof\Http\Middleware\Profile runs early in the middleware stack to capture full request time.
  • Environment Gating: Restrict profiling to specific environments (e.g., local, staging) in config/xhprof.php:
    'enabled' => env('APP_ENV') !== 'production',
    
  • Skip Noisy Routes: Exclude routes from profiling using skip_urls:
    'skip_urls' => [
        'health-check',
        'ping',
        'admin/*',
    ],
    
  • Storage Backend: For high-volume profiling, switch to file storage in config/xhprof.php:
    'storage' => 'file',
    
  • Custom Storage: Extend the package by implementing the Storage interface for S3 or other backends.

Gotchas and Tips

Pitfalls

  1. XHProf Extension Missing:

    • Symptom: Profiles return empty or errors like Call to undefined function xhprof_enable().
    • Fix: Install the extension:
      pecl install xhprof
      
      Add to php.ini:
      extension=xhprof.so
      XHPROF_SAMPLE_RATE=100
      
    • Debug: Verify with php -m | grep xhprof.
  2. Database Storage Bloat:

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

    • Symptom: Profiles show incomplete wall time (e.g., missing middleware execution).
    • Fix: Move \LaracraftTech\Xhprof\Http\Middleware\Profile to the top of the middleware stack in app/Http/Kernel.php.
  4. Case Sensitivity in Skip Rules:

    • Symptom: Routes like /Health are not skipped when skip_urls contains 'health'.
    • Fix: Use exact substrings or regex (if extended):
      'skip_urls' => [
          '/health',
          '/Health',
      ],
      
  5. Blob Data Truncation (MySQL):

    • Symptom: Large profiles are truncated in the database.
    • Fix: Ensure the xhprof_runs table uses LONGTEXT for the data column (handled in v1.0.10+ migrations). If upgrading, run:
      php artisan migrate --force
      
  6. CLI Profiling Overhead:

    • Symptom: Profiling CLI jobs adds significant overhead.
    • Fix: Use sampling (XHPROF_SAMPLE_RATE=10) or profile selectively:
      if (env('PROFILE_CLI')) {
          Xhprof::start('cli-job');
          // ...
          Xhprof::stop();
      }
      

Debugging Tips

  • Check Profiles: Use php artisan xhprof:view to inspect the latest profile.
  • Log Profiles: Save profiles to a file 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 when a regression was introduced:
    git bisect start
    git bisect bad   # Current commit is slow
    git bisect good  # Previous commit was fast
    
    Profile each bisect step to pinpoint the culprit.

Extension Points

  1. Custom Storage Backend:

    • Implement the LaracraftTech\Xhprof\Contracts\Storage interface:
      namespace App\Xhprof;
      
      use LaracraftTech\Xhprof\Contracts\Storage;
      
      class S3Storage implements Storage
      {
          public function save($data, $runId)
          {
              // Save to S3
          }
      
          public function get($runId)
          {
              // Retrieve from S3
          }
      }
      
    • Bind it in a service provider:
      $this->app->bind(
          \LaracraftTech\Xhprof\Contracts\Storage::class,
          App\Xhprof\S3Storage::class
      );
      
  2. Custom Middleware:

    • Extend \LaracraftTech\Xhprof\Http\Middleware\Profile to add
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport