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');
First Use Case: Fetch and list all monitors:
$monitors = $ohDear->monitors();
foreach ($monitors as $monitor) {
echo "Monitor: {$monitor->url} (ID: {$monitor->id})\n";
}
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');
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
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,
]);
Monitor-Status Sync:
// Link monitors to a status page
$ohDear->addStatusPageMonitors($statusPageId, ['monitors' => [123, 456]]);
// 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',
]);
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']
);
});
}
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)
}
}
}
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');
}
}
Validation Errors:
ValidationException for malformed requests:
try {
$ohDear->createMonitor(['url' => 'invalid-url']);
} catch (ValidationException $e) {
dd($e->errors()); // Debug validation failures
}
dd() or log() to inspect validation errors during development.Rate Limiting:
OhDearException for rate limits:
try {
$ohDear->monitors()->all();
} catch (OhDearException $e) {
if ($e->getCode() === 429) {
sleep(60); // Retry after 1 minute
}
}
Monitor Types:
CertificateHealth only applies to HTTP monitors). Verify the monitor type before calling check-specific methods:
if ($monitor->type === 'http') {
$certHealth = $ohDear->certificateHealth($monitor->id);
}
Time Zones:
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');
Pagination:
monitors() return iterators. Fetch all items with:
$monitors = iterator_to_array($ohDear->monitors());
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'),
],
],
]);
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]]);
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,
];
}
}
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';
}
}
Webhooks: Use Oh Dear’s webhook API to trigger Laravel events:
// routes/web.php
Route
How can I help you explore Laravel packages today?