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

Xhgui Collector Laravel Package

perftools/xhgui-collector

Standalone XHProf data collector for storing profiles compatible with XHGUI (0.2–0.9). Supports PHP 5.3+, minimal dependencies, configurable storage/collection. Use via auto_prepend_file (web) or header for CLI. Being phased out; use perftools/php-profiler for new installs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require perftools/xhgui-collector
    
  2. Set Up Environment Variables Configure MongoDB connection and profiling settings via .env:

    XHGUI_MONGO_URI=mongodb://localhost:27017
    XHGUI_MONGO_DB=xhprof
    XHGUI_PROFILING_RATIO=50  # Profile 50% of requests
    XHGUI_PROFILING=enabled
    XHGUI_CONFIG_DIR=/path/to/config
    
  3. Integrate with Laravel Add the header to your bootstrap/app.php (or public/index.php for legacy apps):

    require __DIR__.'/../../vendor/perftools/xhgui-collector/external/header.php';
    
  4. Verify XHGUI Compatibility Ensure your XHGUI instance (v0.2.0–0.9.0) matches the compatibility table.

  5. First Profiling Run Trigger a request or CLI command. Data will auto-save to MongoDB for XHGUI visualization.


First Use Case: Profiling a Laravel API Endpoint

  1. Enable Profiling for a Specific Route Add middleware to toggle profiling dynamically:

    // app/Http/Middleware/ProfileRequests.php
    public function handle($request, Closure $next) {
        if ($request->header('X-Profile')) {
            putenv('XHGUI_PROFILING=enabled');
        }
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // ...
            \App\Http\Middleware\ProfileRequests::class,
        ],
    ];
    
  2. Test with Curl

    curl -H "X-Profile: true" http://your-app.test/api/endpoint
    
  3. Analyze in XHGUI Open http://xhgui-host and filter by your app’s URL.


Implementation Patterns

Workflows

1. Environment-Specific Profiling

Use Laravel’s .env files to control profiling per environment:

# .env.staging
XHGUI_PROFILING_RATIO=10  # Profile 10% of staging requests
XHGUI_PROFILING=enabled

# .env.production
XHGUI_PROFILING_RATIO=1  # Rarely profile in prod

2. Conditional Profiling in Code

Disable profiling for non-critical paths:

// In a controller or service
if (!app()->environment('local')) {
    putenv('XHGUI_PROFILING=disabled');
}

3. Custom ID for Profiling Runs

Override the default ID for structured analysis:

// Before triggering profiling
putenv('XHGUI_PROFILE_ID=feature-x-login-2024');

Integration Tips

Laravel Service Provider

Extend the collector’s config via a service provider:

// app/Providers/ProfilerServiceProvider.php
public function boot() {
    $this->app['config']->set('profiler.skip_built_in', true);
}

Middleware for Selective Profiling

Profile only authenticated users:

// app/Http/Middleware/ProfileAuthUsers.php
public function handle($request, Closure $next) {
    if (auth()->check()) {
        putenv('XHGUI_PROFILING=enabled');
    }
    return $next($request);
}

CLI Script Profiling

Profile Artisan commands:

php -d auto_prepend_file=/vendor/perftools/xhgui-collector/external/header.php artisan migrate

Excluding Built-ins (v1.8.0+)

Add to config/profiler.php:

'skip_built_in' => env('PROFILER_SKIP_BUILT_IN', true),

Now profiling data excludes strlen(), array_map(), etc.


Gotchas and Tips

Pitfalls

  1. Session Locking Issues

    • Problem: Slow session writes (e.g., session()->save()) may block profiling data collection.
    • Fix: Ensure XHGUI_SESSION_CLOSE=true in .env or manually close sessions before profiling:
      session()->save();
      session_write_close();
      
  2. FastCGI Output Buffering

    • Problem: Profiling data may not flush in FastCGI (e.g., Nginx + PHP-FPM).
    • Fix: Enable fastcgi_finish_request in header.php or set:
      ini_set('output_buffering', 'off');
      
  3. MongoDB Schema Mismatches

    • Problem: XHGUI Collector v1.x expects MongoDB schema ≤ 0.7.1. Newer XHGUI versions may break compatibility.
    • Fix: Pin XHGUI to a compatible version or upgrade the collector to match your XHGUI schema.
  4. Environment Variable Overrides

    • Problem: .env variables may be ignored if header.php is included after Laravel’s bootstrapping.
    • Fix: Load the collector before Laravel’s bootstrap/app.php:
      // public/index.php (top of file)
      require __DIR__.'/../vendor/perftools/xhgui-collector/external/header.php';
      
  5. Profiling Ratio Misinterpretation

    • Problem: XHGUI_PROFILING_RATIO=50 profiles 50% of requests, not 50ms per request.
    • Fix: Use XHGUI_PROFILING_RATIO=100 for deterministic profiling (every request).

Debugging Tips

  1. Verify Profiling is Active Check for XHGUI_PROFILING in phpinfo() or log:

    file_put_contents(
        storage_path('logs/profiler-debug.log'),
        print_r(getenv('XHGUI_PROFILING'), true)
    );
    
  2. Inspect MongoDB Data Query the xhprof database to confirm data is stored:

    mongo xhprof --eval 'db.profiles.find().limit(1).pretty()'
    
  3. Check XHGUI Logs Look for errors in xhgui/logs/ (e.g., connection issues to MongoDB).

  4. Disable Caching Ensure OPcache is off during profiling to avoid skewed results:

    php -d opcache.enable=0 artisan your:command
    

Extension Points

  1. Custom Profile ID Logic Override the default ID generation in header.php:

    // Before require 'header.php'
    define('XHGUI_PROFILE_ID', 'custom-' . uniqid());
    
  2. Post-Processing Hooks Add logic after profiling data is collected:

    // In a service provider
    $this->app->afterResolving('profiler', function ($profiler) {
        // Modify $profiler->data before storage
    });
    
  3. Alternative Storage Backends Replace MongoDB with Redis or a custom saver by extending the collector’s Saver class:

    // app/Extensions/XhguiRedisSaver.php
    class XhguiRedisSaver extends \Xhgui\Collector\Saver\MongoSaver {
        public function save($data) {
            // Implement Redis logic
        }
    }
    
  4. Dynamic Profiling Toggle Use Laravel’s app() to enable/disable profiling:

    if (app()->runningInConsole()) {
        putenv('XHGUI_PROFILING=enabled');
    }
    

Configuration Quirks

  1. XHGUI_CONFIG_DIR Priority

    • If set, the collector uses XHGUI_CONFIG_DIR/config.php over environment variables for advanced configs.
  2. replace_url Option

    • Rewrite URLs in profiling data (useful for Docker or reverse proxies):
      putenv('XHGUI_REPLACE_URL=http://old-host,http://new-host');
      
  3. PDO Backend Support (v1.7.0+)

    • Enable PDO for database-agnostic storage:
      putenv('XHGUI_SAVER=pdo');
      
  4. Upload Saver (v1.5.0+)

    • Store profiles as files (useful for air-gapped systems):
      putenv('XHGUI_SAVER=upload');
      putenv('XHGUI_UPLOAD
      
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.
besmartand-pro/php-quality-config
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