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 Setup

  1. Installation:

    composer require blackfire/php-sdk
    

    Ensure your Laravel app has the Blackfire PHP extension installed (or use the PHP Probe fallback).

  2. Environment Configuration: Add Blackfire credentials to .env:

    BLACKFIRE_CLIENT_ID=your_client_id
    BLACKFIRE_CLIENT_TOKEN=your_client_token
    BLACKFIRE_SERVER_ID=your_server_id
    BLACKFIRE_SERVER_TOKEN=your_server_token
    
  3. First Profile: In a Laravel route or controller:

    use Blackfire\Client;
    
    route('profile', function () {
        $client = new Client();
        $client->startScenario('My Laravel App');
    
        // Your code to profile
        User::with('posts')->find(1);
    
        $client->closeScenario();
    });
    
  4. View Results: Profiles will appear in your Blackfire.io dashboard.


First Use Case: Profiling a Laravel Controller

use Blackfire\Client;

class UserController extends Controller
{
    public function show(User $user)
    {
        $client = app(Client::class);
        $client->startScenario('User Show');

        // Profile this entire method
        $posts = $user->posts()->with('comments')->get();

        $client->closeScenario();
        return view('user.show', compact('user', 'posts'));
    }
}

Implementation Patterns

1. Middleware Integration

Profile all requests via middleware:

use Blackfire\Client;

class BlackfireMiddleware extends Middleware
{
    public function handle(Request $request, Closure $next)
    {
        $client = app(Client::class);
        $client->startScenario('HTTP Request: ' . $request->path());

        $response = $next($request);

        $client->closeScenario();
        return $response;
    }
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\BlackfireMiddleware::class,
];

2. Artisan Command Profiling

Profile CLI commands:

use Blackfire\Client;
use Illuminate\Console\Command;

class OptimizeCommand extends Command
{
    protected $signature = 'app:optimize';
    protected $description = 'Optimize the application';

    public function handle()
    {
        $client = app(Client::class);
        $client->startScenario('Artisan Optimize');

        // Your optimization logic
        Artisan::call('cache:clear');
        Artisan::call('config:clear');

        $client->closeScenario();
    }
}

3. Queue Job Profiling

Profile queue workers:

use Blackfire\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function handle()
    {
        $client = app(Client::class);
        $client->startScenario('ProcessPodcast Job');

        // Your job logic
        $podcast = Podcast::find($this->podcastId);
        $podcast->process();

        $client->closeScenario();
    }
}

4. Symfony Event Subscribers

For Laravel apps using Symfony components:

use Blackfire\Client;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class BlackfireSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => 'onKernelRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $client = app(Client::class);
        $client->startScenario('Symfony Request: ' . $event->getRequest()->getPathInfo());

        // Event handling...
    }
}

5. HTTP Client Profiling

Profile HTTP requests with Laravel's HTTP client:

use Blackfire\Client;
use Illuminate\Support\Facades\Http;

$client = app(Client::class);
$client->startScenario('External API Call');

$response = Http::withOptions([
    'blackfire' => [
        'title' => 'GitHub API',
        'url' => 'https://api.github.com',
    ]
])->get('https://api.github.com/user');

$client->closeScenario();

6. Database Query Profiling

Focus on specific queries:

use Blackfire\Client;
use Illuminate\Support\Facades\DB;

$client = app(Client::class);
$client->startScenario('Database Query');

$results = DB::connection('mysql')->select('SELECT * FROM users WHERE active = ?', [1]);

$client->closeScenario();

Gotchas and Tips

1. Configuration Quirks

  • Environment Variables: Ensure BLACKFIRE_CLIENT_ID and BLACKFIRE_CLIENT_TOKEN are set. Without them, profiling will fail silently.
  • Server Tokens: For server-side profiling, BLACKFIRE_SERVER_ID and BLACKFIRE_SERVER_TOKEN are required.
  • Build UUIDs: If using CI/CD, set BLACKFIRE_BUILD_UUID to group profiles logically:
    BLACKFIRE_BUILD_UUID=git-commit-hash
    

2. Common Pitfalls

  • Unclosed Scenarios: Forgetting to call closeScenario() can lead to orphaned profiles or memory leaks. Use a finally block or Laravel's illuminate/support helpers:
    $client->startScenario('My Scenario');
    try {
        // Code to profile
    } finally {
        $client->closeScenario();
    }
    
  • Nested Scenarios: Avoid nesting scenarios (e.g., starting a new scenario inside an existing one). Use sub-titles or tags instead:
    $client->startScenario('User Profile', ['tags' => ['auth']]);
    
  • PHP Probe Fallback: If using the PHP Probe (not recommended for production), ensure xhprof is installed and configured. The probe adds ~5-10% overhead.

3. Debugging

  • Profile Not Ready: If you see ProfileNotReadyException, ensure:
    • The Blackfire PHP extension is loaded (php -m | grep blackfire).
    • The server is online (check Blackfire status).
    • No firewall/proxy is blocking traffic to blackfire.io.
  • Retry Logic: The SDK retries failed profile uploads (default: 3 attempts). Adjust with:
    $client->getProfile($profileId, ['maxRetries' => 5]);
    
  • Logging: Enable debug logs for troubleshooting:
    $client = new Client(['logger' => new \Monolog\Logger('blackfire', [new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG)])]);
    

4. Performance Tips

  • Exclude Common Paths: Profile only critical paths (e.g., exclude health checks):
    if (str_starts_with(request()->path(), '/health')) {
        return response()->json(['status' => 'ok']);
    }
    
  • Use Tags: Tag scenarios for filtering in the Blackfire UI:
    $client->startScenario('API Request', ['tags' => ['api', 'v1']]);
    
  • Avoid Over-Profiling: Profiling too many scenarios can slow down your app. Focus on:
    • Slow endpoints (identify via Laravel Debugbar or telescope).
    • Database-heavy operations.
    • External API calls.

5. Advanced Patterns

  • Custom Metrics: Add custom metrics to profiles:
    $client->addMetric('users_count', User::count());
    $client->addMetric('cache_hits', Cache::stats()['hits'] ?? 0);
    
  • Environment-Specific Config: Load different Blackfire configs per environment:
    $config = config('blackfire.'.app()->environment());
    $client = new Client($config);
    
    Define in config/blackfire.php:
    return [
        'local' => [
            'clientId' => env('BLACKFIRE_CLIENT_ID_LOCAL'),
            'clientToken' => env('BLACKFIRE_CLIENT_TOKEN_LOCAL'),
        ],
        'production' => [
            'clientId' => env('BLACKFIRE_CLIENT_ID'),
            'clientToken' => env('BLACKFIRE_CLIENT_TOKEN'),
            'serverId' => env('BLACKFIRE_SERVER_ID'),
            'serverToken' => env('BLACKFIRE_SERVER_TOKEN'),
        ],
    ];
    
  • BlackfiredHttpClient: For HTTP client profiling, use the built-in BlackfiredHttpClient:
    use Blackfire\Http\BlackfiredHttpClient
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit