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.
Installation:
composer require ohdearapp/ohdear-php-sdk
Authentication:
use OhDear\PhpSdk\OhDear;
$ohDear = new OhDear('your-api-token-here');
Get your API token from Oh Dear API Tokens.
First Use Case: Fetch all monitors to verify connectivity:
foreach ($ohDear->monitors() as $monitor) {
echo "Monitor {$monitor->id}: {$monitor->url} (Status: {$monitor->checkResult()->value})";
}
OhDear\PhpSdk\Dto\* for response structures (e.g., Monitor, CheckSummary).OhDear\PhpSdk\Enums\* (e.g., CheckType, CheckResult) for type-safe operations.// Create monitors dynamically
$monitorIds = [];
foreach ($urls as $url) {
$monitorIds[] = $ohDear->createMonitor([
'url' => $url,
'type' => 'http',
'team_id' => 1,
])->id;
}
// Get monitors by URL pattern (requires manual filtering)
$monitors = $ohDear->monitors()->filter(fn($m) => str_contains($m->url, 'api.example.com'));
// Run uptime check with custom headers
$ohDear->requestCheckRun($checkId, [
'Authorization' => 'Bearer ' . $apiToken,
'X-Custom-Header' => 'value',
]);
// 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(),
]);
// 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',
]);
}
$this->app->singleton(OhDear::class, fn() => new OhDear(config('services.ohdear.token')));
monitor_down):
$ohDear->monitors()->each(fn($monitor) =>
event(new MonitorStatusChanged($monitor->id, $monitor->checkResult()))
);
$monitors = Cache::remember('ohdear_monitors', now()->addHours(1), fn() => $ohDear->monitors());
Rate Limiting:
use OhDear\PhpSdk\Exceptions\OhDearException;
try {
$ohDear->createMonitor($data);
} catch (OhDearException $e) {
if ($e->isRateLimited()) {
sleep($e->retryAfterSeconds);
retry();
}
}
Monitor URL Uniqueness:
monitorByUrl() to check existence first:
if (!$ohDear->monitorByUrl('https://example.com')) {
$ohDear->createMonitor(['url' => 'https://example.com', ...]);
}
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);
}
Time Zone Handling:
$period->startsAt->setTimezone('America/New_York');
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')),
]),
],
]);
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']]
}
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.
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);
});
Batch Processing: For large monitor lists, use chunking to avoid memory issues:
$monitors = $ohDear->monitors();
foreach ($monitors->chunk(50) as $chunk) {
processChunk($chunk);
}
Timeout Adjustments:
$ohDear = new OhDear('token', timeoutInSeconds: 60);
Team ID Validation:
team_id exists before creating monitors/status pages. Use ohDear->me()->teams to list available teams.Check Type Specifics:
requestCheckRun() only works for uptime checks.CheckType::Uptime to ensure type safety.How can I help you explore Laravel packages today?