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

Php Sdk Laravel Package

blackfire/php-sdk

Blackfire PHP SDK provides a client for programmatic profiling with Blackfire, plus integrations like PHPUnit. Includes an optional proxy to inspect profiling traffic and a pure-PHP probe fallback for environments where the Blackfire extension can’t be installed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the SDK:

    composer require blackfire/php-sdk
    

    Ensure your environment has the Blackfire PHP extension installed (or use the PHP Probe fallback for unsupported setups).

  2. First Use Case: Profiling a Laravel Route Add this to a controller or middleware:

    use Blackfire\Client;
    
    public function index()
    {
        $client = new Client();
        $client->startScenario('My Scenario');
    
        // Your code to profile...
        $result = DB::table('users')->get();
    
        $client->endScenario();
        return response()->json($result);
    }
    
  3. First Use Case: PHPUnit Integration Annotate tests with @blackfire:

    use Blackfire\Tests\PhpUnit\BlackfireTestCase;
    
    class UserTest extends BlackfireTestCase
    {
        public function testUserCreation()
        {
            $user = User::create(['name' => 'John']);
            $this->assertDatabaseHas('users', ['name' => 'John']);
        }
    }
    

    Run tests with:

    vendor/bin/phpunit --blackfire
    
  4. Verify Setup Check the Blackfire UI for recorded profiles. If using the PHP Probe, ensure blackfire.php-probe is enabled in your php.ini or Docker config.


Implementation Patterns

Core Workflows

1. Manual Instrumentation (Laravel-Specific)

  • Middleware for HTTP Profiling:

    use Blackfire\Client;
    use Closure;
    
    class BlackfireMiddleware
    {
        public function handle($request, Closure $next)
        {
            $client = new Client();
            $client->startScenario('HTTP Request: ' . $request->path());
    
            $response = $next($request);
    
            $client->endScenario();
            return $response;
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\BlackfireMiddleware::class,
    ];
    
  • Queue Job Profiling:

    use Blackfire\Client;
    
    class ProcessOrderJob implements ShouldQueue
    {
        public function handle()
        {
            $client = new Client();
            $client->startScenario('ProcessOrderJob');
    
            // Job logic...
            $client->endScenario();
        }
    }
    

2. Automated Profiling in CI/CD

  • GitHub Actions Example:
    - name: Profile with Blackfire
      run: |
        composer require blackfire/php-sdk
        vendor/bin/phpunit --blackfire --filter testUserCreation
    
  • Laravel Artisan Commands:
    use Blackfire\Client;
    use Illuminate\Console\Command;
    
    class ProfileCommand extends Command
    {
        protected $signature = 'blackfire:profile {command}';
        protected $description = 'Profile an Artisan command';
    
        public function handle()
        {
            $client = new Client();
            $client->startScenario('Artisan: ' . $this->argument('command'));
    
            $this->call($this->argument('command'));
            $client->endScenario();
        }
    }
    

3. Symfony/Laravel Runtime Integration

  • Laravel Octane: Use the BlackfiredHttpClient for async profiling:

    use Blackfire\Client;
    use Illuminate\Support\Facades\Http;
    
    $client = new Client();
    $blackfiredHttp = $client->getHttpClient();
    
    $response = $blackfiredHttp->get('https://api.example.com/data');
    
  • Symfony Runtime: Leverage the built-in subscriber (no extra config needed in v3.0.0).

4. PHPUnit Integration

  • Custom Annotations: Extend BlackfireTestCase for project-specific annotations:

    use Blackfire\Tests\PhpUnit\BlackfireTestCase;
    
    class PerformanceTestCase extends BlackfireTestCase
    {
        protected function setUp(): void
        {
            parent::setUp();
            $this->blackfire()->setScenario('Performance Regression Test');
        }
    }
    
  • Data Providers:

    public function testMultipleQueries()
    {
        $this->blackfire()->startScenario('Database Queries');
        $this->assertDatabaseHas('users', ['name' => 'Alice']);
        $this->assertDatabaseHas('users', ['name' => 'Bob']);
        $this->blackfire()->endScenario();
    }
    

Integration Tips

Laravel-Specific

  • Service Provider Binding: Bind the Blackfire\Client in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->singleton(Client::class, function () {
            return new Client();
        });
    }
    
  • Event-Based Profiling: Profile specific events (e.g., illuminate.query):

    use Blackfire\Client;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Events;
    
    Events::listen('illuminate.query', function ($query) {
        $client = app(Client::class);
        $client->startScenario('Slow Query: ' . $query->sql);
        DB::connection()->getPdo()->exec($query->sql);
        $client->endScenario();
    });
    

Advanced Patterns

  • Conditional Profiling: Profile only in specific environments (e.g., staging):

    if (app()->environment('staging')) {
        $client->startScenario('Staging Profiling');
        // Code...
        $client->endScenario();
    }
    
  • Profile Groups: Use scenarios to group related profiles (e.g., "Checkout Flow"):

    $client->startScenario('Checkout Flow');
    $client->addJobInScenario('Add to Cart');
    $client->addJobInScenario('Checkout');
    $client->endScenario();
    
  • Custom Metrics: Add custom context to profiles:

    $client->setAttribute('user_id', auth()->id());
    $client->setAttribute('request_id', $request->header('X-Request-ID'));
    

Gotchas and Tips

Pitfalls

  1. Deprecated API in v2.x:

    • Issue: Code using deprecated methods (e.g., Client::createBuild) will fail in v3.0.0.
    • Fix: Update to v3.0.0’s API:
      // Old (v2.x)
      $client->createBuild('My Build');
      
      // New (v3.0.0)
      $client->startScenario('My Scenario');
      
  2. PHP Probe Limitations:

    • Issue: The PHP Probe (fallback for no extension) has higher overhead and fewer features than the native extension.
    • Fix: Use it only for legacy systems or shared hosting. Prefer the native extension for production.
  3. Scenario Naming Collisions:

    • Issue: Duplicate scenario names can obscure profiles in the Blackfire UI.
    • Fix: Include unique identifiers (e.g., request IDs, user IDs):
      $client->startScenario('User ' . auth()->id() . ' - Checkout');
      
  4. HTTP Client Quirks:

    • Issue: BlackfiredHttpClient may not work with relative URLs or custom hosts.
    • Fix: Use absolute URLs or configure the client:
      $client = $blackfireClient->getHttpClient(['base_uri' => 'https://api.example.com']);
      
  5. CI/CD Profiling Failures:

    • Issue: Profiles may not upload in CI due to network restrictions or missing Blackfire agent.
    • Fix: Use the Blackfire proxy or ensure the agent is running:
      services:
        blackfire-agent:
          image: blackfire/blackfire-agent
          ports:
            - "8307:8307"
      
  6. PHPUnit Integration Edge Cases:

    • Issue: @blackfire annotations may not work with custom test suites or parallel testing.
    • Fix: Use programmatic setup:
      $this->blackfire()->startScenario('Custom Test');
      // Test logic...
      $this->blackfire()->endScenario();
      

Debugging Tips

  1. Profile Not Uploading:

    • Check the Blackfire agent is running (blackfire-agent --version).
    • Verify the BLACKFIRE_CLIENT_ID and BLACKFIRE_CLIENT_TOKEN environment variables are set.
    • Enable debug logging:
      $client = new Client(['debug' => true]);
      
  2. High Overhead:

    • Reduce profiling frequency in production (e.g., profile only 1% of requests).
    • Use the `samples
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
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor