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

Ohdear Php Sdk Laravel Package

ohdearapp/ohdear-php-sdk

Official PHP SDK for the Oh Dear monitoring API. Built on Saloon v4, it provides typed DTOs and convenient methods to manage monitors and more. Supports API token auth, configurable timeouts, and clear exceptions for validation and API errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ohdearapp/ohdear-php-sdk
    
  2. Authentication:

    use OhDear\PhpSdk\OhDear;
    $ohDear = new OhDear('your-api-token-here');
    

    Get your API token from Oh Dear API Tokens.

  3. First Use Case: Fetch all monitors to verify connectivity:

    foreach ($ohDear->monitors() as $monitor) {
        echo "Monitor {$monitor->id}: {$monitor->url} (Status: {$monitor->checkResult()->value})";
    }
    

Where to Look First

  • API Documentation: Oh Dear API Docs (critical for understanding available endpoints).
  • DTOs: Explore OhDear\PhpSdk\Dto\* for response structures (e.g., Monitor, CheckSummary).
  • Enums: Use OhDear\PhpSdk\Enums\* (e.g., CheckType, CheckResult) for type-safe operations.

Implementation Patterns

Core Workflows

Monitor Management

  1. Bulk Operations:
    // Create monitors dynamically
    $monitorIds = [];
    foreach ($urls as $url) {
        $monitorIds[] = $ohDear->createMonitor([
            'url' => $url,
            'type' => 'http',
            'team_id' => 1,
        ])->id;
    }
    
  2. Filtering Monitors:
    // Get monitors by URL pattern (requires manual filtering)
    $monitors = $ohDear->monitors()->filter(fn($m) => str_contains($m->url, 'api.example.com'));
    

Check Automation

  1. Trigger Checks on Demand:
    // Run uptime check with custom headers
    $ohDear->requestCheckRun($checkId, [
        'Authorization' => 'Bearer ' . $apiToken,
        'X-Custom-Header' => 'value',
    ]);
    
  2. Maintenance Windows:
    // Schedule maintenance for a deploy
    $ohDear->createMaintenancePeriod([
        'monitor_id' => $monitorId,
        'name' => 'Deploy Maintenance',
        'starts_at' => now()->addMinutes(15)->toDateTimeString(),
        'ends_at' => now()->addMinutes(45)->toDateTimeString(),
    ]);
    

Status Page Integration

  1. Dynamic Updates:
    // Post incident updates from Laravel logs
    if (Log::hasErrors()) {
        $ohDear->createStatusPageUpdate([
            'status_page_id' => $statusPageId,
            'title' => 'Incident Detected',
            'text' => 'Errors found in logs: ' . implode(', ', Log::errors()),
            'severity' => 'high',
        ]);
    }
    

Integration Tips

  1. Laravel Service Provider: Bind the SDK as a singleton for dependency injection:
    $this->app->singleton(OhDear::class, fn() => new OhDear(config('services.ohdear.token')));
    
  2. Event-Driven Triggers: Use Laravel events to hook into monitor status changes (e.g., monitor_down):
    $ohDear->monitors()->each(fn($monitor) =>
        event(new MonitorStatusChanged($monitor->id, $monitor->checkResult()))
    );
    
  3. Caching Responses: Cache monitor lists or check summaries to reduce API calls:
    $monitors = Cache::remember('ohdear_monitors', now()->addHours(1), fn() => $ohDear->monitors());
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • Oh Dear’s API enforces rate limits.
    • Solution: Implement exponential backoff for retries:
      use OhDear\PhpSdk\Exceptions\OhDearException;
      try {
          $ohDear->createMonitor($data);
      } catch (OhDearException $e) {
          if ($e->isRateLimited()) {
              sleep($e->retryAfterSeconds);
              retry();
          }
      }
      
  2. Monitor URL Uniqueness:

    • Duplicate URLs may cause conflicts. Use monitorByUrl() to check existence first:
      if (!$ohDear->monitorByUrl('https://example.com')) {
          $ohDear->createMonitor(['url' => 'https://example.com', ...]);
      }
      
  3. Check Result Interpretation:

    • CheckResult::Warning means the primary location is down, but a secondary location is reachable. Handle this case explicitly:
      if ($monitor->checkResult()->isWarning()) {
          notify('Partial outage detected for ' . $monitor->url);
      }
      
  4. Time Zone Handling:

    • API timestamps use UTC. Convert to local time for display:
      $period->startsAt->setTimezone('America/New_York');
      

Debugging

  1. Enable Saloon Logging: Configure Saloon to log requests/responses:

    $ohDear = new OhDear('token', [
        'saloon' => [
            'logger' => new \Monolog\Logger('ohdear', [
                new \Monolog\Handler\StreamHandler(storage_path('logs/ohdear.log')),
            ]),
        ],
    ]);
    
  2. Validation Errors:

    • ValidationException provides detailed error messages:
      try {
          $ohDear->createMonitor(['url' => 'invalid-url']);
      } catch (ValidationException $e) {
          dd($e->errors()); // ['url' => ['must be a valid URL']]
      }
      

Extension Points

  1. Custom DTOs: Extend DTOs to add computed properties (e.g., Monitor with isCritical()):

    class ExtendedMonitor extends \OhDear\PhpSdk\Dto\Monitor {
        public function isCritical(): bool {
            return $this->checkResult()->isDown() && str_contains($this->url, 'critical.');
        }
    }
    

    Override the SDK’s DTO mapping in your service provider.

  2. Webhook Listeners: Use Oh Dear’s webhooks to trigger Laravel jobs:

    Route::post('/ohdear/webhook', function (Request $request) {
        $event = $request->json()->all();
        HandleMonitorEvent::dispatch($event);
    });
    
  3. Batch Processing: For large monitor lists, use chunking to avoid memory issues:

    $monitors = $ohDear->monitors();
    foreach ($monitors->chunk(50) as $chunk) {
        processChunk($chunk);
    }
    

Configuration Quirks

  1. Timeout Adjustments:

    • Default timeout is 10 seconds. Increase for slow monitors:
      $ohDear = new OhDear('token', timeoutInSeconds: 60);
      
    • Warning: High timeouts may trigger API rate limits.
  2. Team ID Validation:

    • Always validate team_id exists before creating monitors/status pages. Use ohDear->me()->teams to list available teams.
  3. Check Type Specifics:

    • Not all checks support all operations. For example:
      • requestCheckRun() only works for uptime checks.
      • Use CheckType::Uptime to ensure type safety.
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai