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 Contracts Laravel Package

aeatech/snapshot-profiler-contracts

Contracts/interfaces for integrating a snapshot-based profiler into Laravel/PHP apps. Provides the core abstractions used by the Snapshot Profiler package ecosystem for capturing, storing, and reporting performance snapshots across implementations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require aeatech/snapshot-profiler-contracts
    
  2. First Use Case: Define a Profiler Contract Create a simple profiler class implementing the core interface:

    use Aeatech\SnapshotProfilerContracts\Profiler;
    
    class MyProfiler implements Profiler
    {
        public function start(string $name): void
        {
            // Start profiling logic
        }
    
        public function stop(string $name): void
        {
            // Stop profiling logic
        }
    
        public function getSnapshot(string $name): array
        {
            return ['duration' => 100, 'memory' => '1MB'];
        }
    }
    
  3. Register the Profiler Bind your implementation in config/app.php or a service provider:

    $app->bind(Profiler::class, MyProfiler::class);
    
  4. Basic Usage Inject the profiler into a controller or service:

    use Aeatech\SnapshotProfilerContracts\Profiler;
    
    class MyController
    {
        public function __construct(private Profiler $profiler) {}
    
        public function index()
        {
            $this->profiler->start('route.index');
            // ... logic
            $this->profiler->stop('route.index');
            $snapshot = $this->profiler->getSnapshot('route.index');
        }
    }
    

Implementation Patterns

Dependency Injection Workflow

  • Service Binding: Prefer binding interfaces to concrete implementations in a service provider for flexibility.
    $app->singleton(Profiler::class, function ($app) {
        return new MyProfiler($app['log']);
    });
    
  • Contextual Binding: Use when multiple profilers are needed (e.g., per request or tenant).
    $app->bindWhen(Profiler::class, function ($app, $context) {
        return new TenantProfiler($context['tenantId']);
    });
    

Middleware Integration

Leverage middleware to auto-profile routes:

use Aeatech\SnapshotProfilerContracts\Profiler;

class ProfileMiddleware
{
    public function __construct(private Profiler $profiler) {}

    public function handle($request, Closure $next)
    {
        $this->profiler->start('middleware.' . $request->route()->getName());
        $response = $next($request);
        $this->profiler->stop('middleware.' . $request->route()->getName());
        return $response;
    }
}

Event-Based Profiling

Attach profilers to Laravel events (e.g., Illuminate\Queue\Jobs\JobProcessed):

use Aeatech\SnapshotProfilerContracts\Profiler;

class JobProfiler
{
    public function __construct(private Profiler $profiler) {}

    public function handle(JobProcessed $event)
    {
        $this->profiler->start('job.' . $event->job->resolveName());
        // ... post-job logic
        $this->profiler->stop('job.' . $event->job->resolveName());
    }
}

Decorator Pattern for Extensibility

Wrap the profiler to add cross-cutting concerns (e.g., logging):

class LoggingProfiler implements Profiler
{
    public function __construct(
        private Profiler $profiler,
        private LoggerInterface $logger
    ) {}

    public function start(string $name): void
    {
        $this->logger->info("Profiling started: {$name}");
        $this->profiler->start($name);
    }

    // Delegate other methods...
}

Gotchas and Tips

Pitfalls

  1. Naming Collisions

    • Ensure unique names for start()/stop() pairs to avoid corrupting snapshots.
    • Use namespaced keys (e.g., controller.user.show).
  2. Snapshot Leaks

    • Unmatched start()/stop() calls will cause memory leaks. Use a try-finally pattern:
      try {
          $this->profiler->start('operation');
          // ... logic
      } finally {
          $this->profiler->stop('operation');
      }
      
  3. Performance Overhead

    • Profiling adds latency. Disable in production via config:
      'profiling' => env('APP_ENV') !== 'production',
      
  4. Thread Safety

    • The package assumes single-threaded use (common in Laravel). For queues/workers, use request-scoped bindings:
      $app->when(Profiler::class)
          ->needs('$request')
          ->give(fn () => request());
      

Debugging Tips

  • Verify Snapshots: Log snapshots to ensure data integrity:
    $this->profiler->getSnapshot('name'); // Debug output
    
  • Check Bindings: Use php artisan container:inspect Aeatech\SnapshotProfilerContracts\Profiler to verify registrations.
  • Test Edge Cases: Profile nested operations (e.g., middleware + controller) to catch missing stops.

Extension Points

  1. Custom Metrics Extend the Profiler interface to add methods like:

    public function recordMetric(string $name, string $key, mixed $value): void;
    

    Then implement in your concrete class.

  2. Storage Backends Decouple snapshots from the profiler by adding a SnapshotStorage interface:

    interface SnapshotStorage {
        public function store(string $name, array $data): void;
        public function retrieve(string $name): ?array;
    }
    
  3. Async Profiling Use Laravel’s queue to offload snapshot processing:

    $this->dispatch(new StoreSnapshotJob($name, $snapshot));
    
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