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 API (built on Saloon v4). Authenticate with an API token, manage monitors, fetch user info, and more with typed DTOs and iterators. Configurable timeouts and clear exceptions for validation and API errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the SDK:
    composer require ohdearapp/ohdear-php-sdk
    
  2. Authenticate:
    use OhDear\PhpSdk\OhDear;
    $ohDear = new OhDear('your-api-token');
    
  3. First Use Case: Fetch your user info to verify authentication:
    $user = $ohDear->me();
    echo "Authenticated as: {$user->email}";
    

Where to Look First

  • API Documentation: Oh Dear API Docs (critical for understanding endpoints and payloads).
  • SDK Methods: The OhDear class is the main entry point. Methods like monitors(), statusPages(), and checkSummary() are the most commonly used.
  • DTOs: Data Transfer Objects (e.g., Monitor, StatusPage, CheckSummary) are pre-loaded with type-safe properties and helper methods (e.g., checkResult()->isUp()).

Implementation Patterns

Core Workflows

1. Monitor Management

  • Create and List Monitors:
    // Create a monitor
    $monitor = $ohDear->createMonitor([
        'url' => 'https://example.com',
        'type' => 'http',
        'team_id' => 1,
        'checks' => ['uptime', 'ssl_certificate'],
    ]);
    
    // List all monitors (returns an iterator)
    foreach ($ohDear->monitors() as $monitor) {
        echo "Monitor {$monitor->id}: {$monitor->url}\n";
    }
    
  • Bulk Operations: Use monitorByUrl() to fetch a monitor by URL, then update/delete as needed:
    $monitor = $ohDear->monitorByUrl('https://example.com');
    $ohDear->deleteMonitor($monitor->id);
    

2. Status Page Integration

  • Dynamic Status Updates: Fetch monitor statuses and update a status page dynamically:
    $statusPage = $ohDear->statusPage($statusPageId);
    $updates = $ohDear->statusPageUpdates($statusPageId);
    
    foreach ($ohDear->monitors() as $monitor) {
        if ($monitor->checkResult()->isDown()) {
            $ohDear->createStatusPageUpdate([
                'status_page_id' => $statusPageId,
                'title' => 'Down: ' . $monitor->url,
                'text' => 'Monitor is down. Investigating...',
                'severity' => 'high',
            ]);
        }
    }
    

3. Check-Specific Actions

  • Trigger Immediate Checks: Useful for CI/CD pipelines or pre-deployment checks:
    $check = $ohDear->requestCheckRun($checkId, [
        'User-Agent' => 'CI/CD Pipeline',
    ]);
    
  • Temporary Snoozing: Disable notifications during maintenance:
    $ohDear->snoozeCheck($checkId, 3600); // Snooze for 1 hour
    

4. Certificate Health Monitoring

  • Automated Alerts: Check certificate validity and expire soon:
    $certHealth = $ohDear->certificateHealth($monitorId);
    if (!$certHealth->isHealthy()) {
        $daysUntilExpiry = $certHealth->getDaysUntilExpiry();
        if ($daysUntilExpiry < 30) {
            // Trigger alert or renewal process
        }
    }
    

5. Uptime Metrics for Analytics

  • Performance Tracking: Log metrics to your database for trend analysis:
    $metrics = $ohDear->httpUptimeMetrics($monitorId, '-7 days', 'now');
    foreach ($metrics as $metric) {
        DB::table('uptime_metrics')->insert([
            'monitor_id' => $monitorId,
            'date' => $metric->date,
            'total_time' => $metric->totalTimeInSeconds,
            'created_at' => now(),
        ]);
    }
    

Integration Tips

  • Laravel Service Provider: Bind the SDK to the container for dependency injection:

    // config/services.php
    'ohdear' => [
        'api_token' => env('OHDEAR_API_TOKEN'),
        'timeout' => 30,
    ];
    
    // AppServiceProvider
    public function register()
    {
        $this->app->singleton(OhDear::class, function ($app) {
            return new OhDear(
                $app['config']['services.ohdear.api_token'],
                timeoutInSeconds: $app['config']['services.ohdear.timeout']
            );
        });
    }
    

    Then inject OhDear into controllers/services.

  • Artisan Commands: Create commands for manual checks (e.g., php artisan ohdear:check-monitor):

    use OhDear\PhpSdk\OhDear;
    use OhDear\PhpSdk\Enums\CheckType;
    
    class CheckMonitorCommand extends Command
    {
        protected $signature = 'ohdear:check-monitor {monitorId}';
        protected $description = 'Trigger an immediate check for a monitor';
    
        public function handle(OhDear $ohDear)
        {
            $monitor = $ohDear->monitor($this->argument('monitorId'));
            $check = $ohDear->requestCheckRun($monitor->checks[0]->id);
    
            $this->info("Triggered check for {$monitor->url}. Check ID: {$check->id}");
        }
    }
    
  • Event Listeners: Listen for monitor status changes (e.g., via webhooks) and trigger Laravel events:

    // Example: Listen for status page updates
    $ohDear->listenForStatusPageUpdates($statusPageId, function ($update) {
        event(new StatusPageUpdated($update));
    });
    
  • Caching: Cache monitor data to reduce API calls (e.g., every 5 minutes):

    $monitors = Cache::remember('ohdear_monitors', 300, function () use ($ohDear) {
        return iterator_to_array($ohDear->monitors());
    });
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

    • Oh Dear’s API has rate limits (e.g., 60 requests/minute). The SDK does not enforce this, so implement retries with exponential backoff:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = HttpClient::create([
          'timeout' => 30,
          'retry_on_status' => [429],
          'retry_delay' => RetryStrategy::DELAY_MILLISECONDS,
      ]);
      
    • Tip: Use the timeoutInSeconds parameter in the OhDear constructor to avoid hanging.
  2. Monitor Type Validation:

    • The type field for monitors must match Oh Dear’s supported types (http, ping, tcp). Invalid types throw ValidationException.
    • Tip: Use the CheckType enum for check-specific operations to avoid typos.
  3. Date/Time Formatting:

    • API endpoints expect ISO 8601 timestamps (e.g., '2024-01-01T00:00:00Z'). Use Carbon for consistency:
      $now = Carbon::now()->toAtomString();
      
  4. Team ID Requirement:

    • Most endpoints require a team_id. If omitted, the SDK defaults to the authenticated user’s primary team, but explicit IDs are safer for multi-team setups.
  5. Pagination:

    • Some endpoints (e.g., monitors()) return iterators. To fetch all items, convert to an array:
      $monitors = iterator_to_array($ohDear->monitors());
      
  6. Check IDs vs. Monitor IDs:

    • Confusingly, requestCheckRun() uses check IDs, not monitor IDs. Fetch checks first:
      $monitor = $ohDear->monitor($monitorId);
      $check = $monitor->checks->first(); // Get the first check
      $ohDear->requestCheckRun($check->id);
      

Debugging

  1. Enable Saloon Debugging: The SDK uses Saloon. Enable debug mode to log requests/responses:

    $ohDear = new OhDear('your-api-token', debug: true);
    

    Or configure Saloon globally in config/saloon.php:

    'debug' => env('APP_DEBUG'),
    
  2. Handle Exceptions Gracefully:

    • Catch OhDearException for API errors and ValidationException for input validation:
      try {
          $ohDear->createMonitor(['url' => 'invalid-url']);
      } catch (ValidationException $e) {
          Log::error('Oh Dear validation error:', $e->
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport