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');
    
  3. First Use Case: Fetch and list all monitors:

    $monitors = $ohDear->monitors();
    foreach ($monitors as $monitor) {
        echo "Monitor: {$monitor->url} (ID: {$monitor->id})\n";
    }
    

Key Starting Points

  • API Docs: Refer to Oh Dear API Documentation for endpoint details.
  • Saloon Under the Hood: The SDK uses Saloon for HTTP requests. Familiarity with Saloon’s concepts (e.g., DTOs, requests) helps with customization.

Implementation Patterns

Core Workflows

Monitor Management

  1. Create and Manage Monitors:

    // Create
    $monitor = $ohDear->createMonitor([
        'url' => 'https://example.com',
        'type' => 'http',
        'team_id' => 1,
    ]);
    
    // Update (via PATCH endpoint)
    $ohDear->updateMonitor($monitor->id, ['name' => 'Updated Monitor']);
    
    // Bulk Actions
    $ohDear->deleteMonitor($monitor->id);
    $ohDear->addToBrokenLinksWhitelist($monitor->id, 'https://example.com/skip');
    
  2. Check-Specific Actions:

    // Trigger a check run with custom headers
    $check = $ohDear->requestCheckRun($checkId, [
        'User-Agent' => 'CustomAgent/1.0',
    ]);
    
    // Snooze notifications
    $ohDear->snoozeCheck($checkId, 3600); // 1 hour
    

Status Pages

  1. Dynamic Updates:

    // Create a status page update from a template
    $template = $ohDear->statusPageUpdateTemplates()->first();
    $update = $ohDear->createStatusPageUpdate([
        'status_page_id' => $statusPageId,
        'title' => $template->title,
        'text' => $template->text,
        'severity' => $template->severity,
    ]);
    
  2. Monitor-Status Sync:

    // Link monitors to a status page
    $ohDear->addStatusPageMonitors($statusPageId, ['monitors' => [123, 456]]);
    

Maintenance Windows

  1. Scheduled vs. Ad-Hoc:
    // Ad-hoc maintenance (1 hour)
    $ohDear->startMaintenancePeriod($monitorId, 3600, 'Emergency Fix');
    
    // Scheduled maintenance
    $ohDear->createMaintenancePeriod([
        'monitor_id' => $monitorId,
        'starts_at' => '2024-12-25 02:00:00',
        'ends_at' => '2024-12-25 06:00:00',
        'name' => 'Holiday Maintenance',
    ]);
    

Integration Tips

  1. Laravel Service Provider: Bind the SDK to Laravel’s container for dependency injection:

    // config/services.php
    'ohdear' => [
        'token' => env('OHDEAR_API_TOKEN'),
        'timeout' => env('OHDEAR_TIMEOUT', 10),
    ];
    
    // AppServiceProvider
    public function register()
    {
        $this->app->singleton(OhDear::class, function ($app) {
            return new OhDear(
                $app['config']['services.ohdear.token'],
                timeoutInSeconds: $app['config']['services.ohdear.timeout']
            );
        });
    }
    
  2. Event-Driven Workflows: Use Laravel’s scheduler or queues to run periodic checks:

    // app/Console/Commands/CheckMonitors.php
    public function handle()
    {
        $monitors = $ohDear->monitors();
        foreach ($monitors as $monitor) {
            $checkSummary = $ohDear->checkSummary($monitor->id, CheckType::Uptime);
            if ($checkSummary->checkResult()->isDown()) {
                // Trigger alert (e.g., Slack, email)
            }
        }
    }
    
  3. DTO Extensions: Extend DTOs (e.g., Monitor, CheckSummary) to add custom logic:

    use OhDear\PhpSdk\Dto\Monitor;
    
    class ExtendedMonitor extends Monitor
    {
        public function isCritical(): bool
        {
            return $this->tags->contains('critical');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Validation Errors:

    • Always catch ValidationException for malformed requests:
      try {
          $ohDear->createMonitor(['url' => 'invalid-url']);
      } catch (ValidationException $e) {
          dd($e->errors()); // Debug validation failures
      }
      
    • Tip: Use dd() or log() to inspect validation errors during development.
  2. Rate Limiting:

    • Oh Dear’s API has rate limits (e.g., 60 requests/minute). Handle OhDearException for rate limits:
      try {
          $ohDear->monitors()->all();
      } catch (OhDearException $e) {
          if ($e->getCode() === 429) {
              sleep(60); // Retry after 1 minute
          }
      }
      
  3. Monitor Types:

    • Not all checks are available for all monitor types (e.g., CertificateHealth only applies to HTTP monitors). Verify the monitor type before calling check-specific methods:
      if ($monitor->type === 'http') {
          $certHealth = $ohDear->certificateHealth($monitor->id);
      }
      
  4. Time Zones:

    • Dates in the API (e.g., starts_at, ends_at) are in UTC. Convert to local time when displaying to users:
      use Carbon\Carbon;
      $localTime = Carbon::parse($period->startsAt)->timezone('America/New_York');
      
  5. Pagination:

    • Methods like monitors() return iterators. Fetch all items with:
      $monitors = iterator_to_array($ohDear->monitors());
      

Debugging

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

    $ohDear = new OhDear('your-token', [
        'timeoutInSeconds' => 10,
        'saloon' => [
            'log' => [
                'enabled' => true,
                'path' => storage_path('logs/ohdear.log'),
            ],
        ],
    ]);
    
  2. Mocking for Tests: Use Saloon’s mocking capabilities to test without hitting the API:

    use OhDear\PhpSdk\Requests\Monitors\GetMonitorsRequest;
    
    $mock = new MockHttpClient();
    $mock->shouldReceive('send')
        ->once()
        ->andReturn(new GetMonitorsResponse([new Monitor()]));
    
    $ohDear = new OhDear('token', ['saloon' => ['connector' => $mock]]);
    

Extension Points

  1. Custom Requests: Extend Saloon’s Request classes to add custom endpoints. Example:

    namespace App\OhDear\Requests;
    
    use OhDear\PhpSdk\OhDearRequest;
    
    class CustomCheckRequest extends OhDearRequest
    {
        protected string $endpoint = 'custom/checks';
        protected string $method = 'POST';
    
        public function resolveEndpoint(): string
        {
            return $this->endpoint . '/' . $this->monitorId;
        }
    
        public function resolveBody(): array
        {
            return [
                'monitor_id' => $this->monitorId,
                'custom_data' => $this->customData,
            ];
        }
    }
    
  2. DTO Customization: Override DTO methods to add business logic:

    namespace App\OhDear\Dto;
    
    use OhDear\PhpSdk\Dto\CheckSummary;
    
    class CustomCheckSummary extends CheckSummary
    {
        public function isSeverelyDown(): bool
        {
            return $this->checkResult()->isDown() &&
                   $this->result === 'failed';
        }
    }
    
  3. Webhooks: Use Oh Dear’s webhook API to trigger Laravel events:

    // routes/web.php
    Route
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony