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

Snapshot Profiler Xhprof Laravel Package

aeatech/snapshot-profiler-xhprof

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aeatech/snapshot-profiler-xhprof
    
  2. Enable XHProf

    • Ensure xhprof PHP extension is installed and enabled in php.ini:
      extension=xhprof.so
      
    • Verify with:
      php -m | grep xhprof
      
  3. Basic Configuration Add to config/app.php:

    'snapshot-profiler' => [
        'driver' => \Aeatech\SnapshotProfiler\XhProf\XhProfDriver::class,
        'storage' => storage_path('app/profiler'),
    ],
    
  4. First Profiling Run Use the facade to trigger profiling:

    use Aeatech\SnapshotProfiler\Facades\Profiler;
    
    Profiler::start('user-action');
    // Your code to profile...
    Profiler::stop();
    
  5. View Results Profiles are saved to storage/app/profiler as JSON files. Use tools like XHProf UI to analyze.


Implementation Patterns

Workflow Integration

  1. Middleware for Automatic Profiling Create middleware to profile requests:

    namespace App\Http\Middleware;
    
    use Aeatech\SnapshotProfiler\Facades\Profiler;
    use Closure;
    
    class ProfileRequests
    {
        public function handle($request, Closure $next)
        {
            Profiler::start('request-' . $request->path());
            $response = $next($request);
            Profiler::stop();
            return $response;
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\ProfileRequests::class,
    ];
    
  2. Conditional Profiling Use environment-based profiling:

    if (app()->environment('production') && config('profiler.enabled')) {
        Profiler::start('critical-path');
        // ...
        Profiler::stop();
    }
    
  3. Tagging and Metadata Attach metadata to profiles:

    Profiler::start('user-action', [
        'user_id' => auth()->id(),
        'route' => route()->getName(),
    ]);
    
  4. Batch Profiling Profile multiple actions in a single run:

    Profiler::start('batch-job');
    // Action 1
    Profiler::snapshot('action-1');
    // Action 2
    Profiler::snapshot('action-2');
    Profiler::stop();
    
  5. Queue Job Profiling Profile long-running jobs:

    namespace App\Jobs;
    
    use Aeatech\SnapshotProfiler\Facades\Profiler;
    use Illuminate\Bus\Queueable;
    
    class ProcessData implements Queueable
    {
        public function handle()
        {
            Profiler::start('process-data-job');
            // Job logic...
            Profiler::stop();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. XHProf Extension Missing

    • Symptom: Profiles return empty or errors.
    • Fix: Install the xhprof extension and restart PHP-FPM/web server.
      pecl install xhprof
      
      For Ubuntu/Debian:
      sudo apt-get install php-xhprof
      
  2. Storage Permissions

    • Symptom: Profiles fail to save.
    • Fix: Ensure the storage/app/profiler directory is writable:
      mkdir -p storage/app/profiler
      chmod -R 775 storage/app/profiler
      
  3. Memory Overhead

    • Symptom: High memory usage in production.
    • Fix: Limit profiling to critical paths or use sampling:
      Profiler::setSamplingRate(10); // Profile 1 in 10 calls
      
  4. Incompatibility with OPcache

    • Symptom: Profiles show incorrect or missing data.
    • Fix: Disable OPcache for profiling runs or ensure xhprof is loaded after OPcache in php.ini.
  5. Race Conditions in Multi-Threaded Environments

    • Symptom: Corrupted profile data.
    • Fix: Avoid profiling in multi-threaded contexts (e.g., Laravel queues with sync driver). Use database or redis drivers instead.

Debugging Tips

  1. Verify XHProf is Active Run a test script:

    <?php
    if (!function_exists('xhprof_enable')) {
        die('XHProf is not enabled!');
    }
    xhprof_enable();
    sleep(1);
    $data = xhprof_disable();
    file_put_contents('test.xhprof', serialize($data));
    echo "Profile saved to test.xhprof";
    

    If this fails, check phpinfo() for xhprof or consult your server admin.

  2. Check Profile Files Inspect raw JSON output for errors:

    cat storage/app/profiler/latest.json | jq
    

    Use jq to validate structure.

  3. Log Profiling Errors Add error handling:

    try {
        Profiler::start('test');
        // ...
        Profiler::stop();
    } catch (\Exception $e) {
        \Log::error('Profiling failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Storage Drivers Extend Aeatech\SnapshotProfiler\Contracts\StorageDriver to save profiles to S3, databases, etc.:

    namespace App\Profiler;
    
    use Aeatech\SnapshotProfiler\Contracts\StorageDriver;
    
    class S3StorageDriver implements StorageDriver
    {
        public function save(string $name, array $data): void
        {
            // Custom S3 logic
        }
    }
    

    Register in config:

    'storage' => \App\Profiler\S3StorageDriver::class,
    
  2. Post-Processing Hooks Use events to process profiles after saving:

    // In a service provider
    Profiler::afterSave(function ($name, $data) {
        // Send to monitoring system, etc.
    });
    
  3. Custom Metrics Extend the profiler to capture additional metrics (e.g., database queries):

    Profiler::customMetric('db', 'query_time', 150);
    
  4. UI Integration Build a custom dashboard using the raw JSON data:

    $profile = Profiler::load('latest');
    // Render with Blade or API
    

Performance Considerations

  • Sampling: Use Profiler::setSamplingRate() to reduce overhead.
  • Exclusion Lists: Skip profiling for known low-value paths:
    Profiler::exclude(['/health', '/ping']);
    
  • Batch Processing: Process profiles asynchronously to avoid blocking requests:
    Profiler::afterSave(function ($name, $data) {
        dispatch(new ProcessProfileJob($name, $data));
    });
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky