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

Laminas Diagnostics Laravel Package

laminas/laminas-diagnostics

Run health checks for your PHP/Laminas apps and environments. laminas-diagnostics provides diagnostic tests and reporting for common issues, with an extensible API for custom checks and CI-friendly output.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laminas/laminas-diagnostics
    

    Add the Laminas\Diagnostics\DiagnosticListener to your Laravel service container (e.g., in AppServiceProvider):

    $this->app->bind('diagnosticListener', function ($app) {
        return new \Laminas\Diagnostics\DiagnosticListener();
    });
    
  2. First Use Case:

    • Check PHP Environment: Use the EnvironmentDiagnostic to verify PHP settings:
      use Laminas\Diagnostics\DiagnosticListener;
      use Laminas\Diagnostics\Diagnostic\EnvironmentDiagnostic;
      
      $listener = $this->app->make('diagnosticListener');
      $diagnostic = new EnvironmentDiagnostic();
      $listener->addDiagnostic($diagnostic);
      
      $result = $listener->run();
      dd($result); // Inspect PHP environment (memory, extensions, etc.)
      
  3. Where to Look First:

    • Laminas Diagnostics Documentation (if available).
    • src/Diagnostic/ for built-in diagnostics (e.g., EnvironmentDiagnostic, MemoryDiagnostic).
    • src/Listener/ for event-driven diagnostics (e.g., DiagnosticListener).

Implementation Patterns

Common Workflows

  1. Pre-Request Diagnostics: Use middleware to run diagnostics before critical operations (e.g., API requests):

    namespace App\Http\Middleware;
    
    use Closure;
    use Laminas\Diagnostics\DiagnosticListener;
    
    class DiagnosticsMiddleware
    {
        public function handle($request, Closure $next)
        {
            $listener = app('diagnosticListener');
            $listener->addDiagnostic(new \Laminas\Diagnostics\Diagnostic\MemoryDiagnostic());
            $result = $listener->run();
    
            // Log or store results (e.g., in a database or cache)
            cache()->put('diagnostics', $result, now()->addHours(1));
    
            return $next($request);
        }
    }
    
  2. Custom Diagnostics: Extend AbstractDiagnostic to create domain-specific checks:

    namespace App\Diagnostics;
    
    use Laminas\Diagnostics\Diagnostic\AbstractDiagnostic;
    
    class DatabaseConnectionDiagnostic extends AbstractDiagnostic
    {
        public function diagnose()
        {
            try {
                \DB::connection()->getPdo();
                return $this->createOk('Database connection is healthy.');
            } catch (\Exception $e) {
                return $this->createFail('Database connection failed: ' . $e->getMessage());
            }
        }
    }
    

    Register it in a service provider:

    $this->app->bind('databaseDiagnostic', function ($app) {
        return new DatabaseConnectionDiagnostic();
    });
    
  3. Event-Driven Diagnostics: Attach diagnostics to Laravel events (e.g., Illuminate\Queue\Events\JobProcessed):

    use Laminas\Diagnostics\DiagnosticListener;
    use Illuminate\Queue\Events\JobProcessed;
    
    Event::listen(JobProcessed::class, function ($event) {
        $listener = app('diagnosticListener');
        $listener->addDiagnostic(new \App\Diagnostics\QueueDiagnostic());
        $result = $listener->run();
        // Handle results (e.g., alert on failures)
    });
    

Integration Tips

  • Laravel Logging: Integrate results with Laravel’s logging system:

    $result = $listener->run();
    foreach ($result as $diagnostic) {
        if ($diagnostic->isOk()) {
            \Log::info($diagnostic->getMessage());
        } else {
            \Log::error($diagnostic->getMessage());
        }
    }
    
  • Scheduling: Run diagnostics via Laravel’s scheduler (e.g., nightly checks):

    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('diagnostics:run')->daily();
    }
    

    Create a custom Artisan command:

    php artisan make:command DiagnosticsRun
    
  • API Endpoints: Expose diagnostics via an API route:

    Route::get('/diagnostics', function () {
        $listener = app('diagnosticListener');
        $listener->addDiagnostic(new \Laminas\Diagnostics\Diagnostic\EnvironmentDiagnostic());
        $result = $listener->run();
        return response()->json($result);
    });
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Running diagnostics in production can impact performance. Use sparingly or cache results.
    • Fix: Schedule diagnostics during low-traffic periods or use a queue.
  2. Diagnostic Order:

    • Diagnostics run in the order they’re added. Critical checks should be first.
    • Fix: Use DiagnosticListener::setDiagnostics() to enforce order.
  3. False Positives/Negatives:

    • Custom diagnostics may misreport issues (e.g., flaky database checks).
    • Fix: Add retries or implement idempotency in custom diagnostics.
  4. Laravel-Specific Quirks:

    • Some Laminas diagnostics assume PSR-15 middleware or other non-Laravel patterns.
    • Fix: Adapt or wrap diagnostics in Laravel-compatible layers (e.g., middleware).

Debugging

  1. Verbose Output: Enable debug mode for detailed diagnostic output:

    $diagnostic = new EnvironmentDiagnostic();
    $diagnostic->setDebug(true);
    
  2. Logging Levels: Use Laravel’s log levels to filter diagnostic output:

    if (!$diagnostic->isOk()) {
        \Log::warning('Diagnostic failed: ' . $diagnostic->getMessage());
    }
    
  3. Testing: Mock diagnostics in unit tests:

    $mockDiagnostic = $this->createMock(\Laminas\Diagnostics\Diagnostic\DiagnosticInterface::class);
    $mockDiagnostic->method('diagnose')->willReturn($this->createOk('Test passed'));
    $listener->addDiagnostic($mockDiagnostic);
    

Tips

  1. Combine Diagnostics: Use CompositeDiagnostic to group related checks:

    use Laminas\Diagnostics\Diagnostic\CompositeDiagnostic;
    
    $composite = new CompositeDiagnostic();
    $composite->addDiagnostic(new EnvironmentDiagnostic());
    $composite->addDiagnostic(new MemoryDiagnostic());
    $listener->addDiagnostic($composite);
    
  2. Configuration: Store diagnostic thresholds in config/diagnostics.php:

    return [
        'memory' => [
            'warning' => 512, // MB
            'critical' => 1024,
        ],
    ];
    

    Load config in diagnostics:

    $memoryLimit = config('diagnostics.memory.warning');
    
  3. Notifications: Integrate with Laravel Notifications for alerts:

    if (!$diagnostic->isOk()) {
        Notification::route('mail', 'admin@example.com')
                    ->notify(new DiagnosticFailed($diagnostic));
    }
    
  4. Extension Points:

    • Override DiagnosticListener to add custom logic (e.g., filtering, formatting).
    • Extend AbstractDiagnostic for reusable diagnostic logic (e.g., shared setup/teardown).
  5. Documentation: Document custom diagnostics in a README or Swagger/OpenAPI specs for API endpoints.

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
spatie/mailcoach-vapor