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.
composer require ohdearapp/ohdear-php-sdk
use OhDear\PhpSdk\OhDear;
$ohDear = new OhDear('your-api-token');
$user = $ohDear->me();
echo "Authenticated as: {$user->email}";
OhDear class is the main entry point. Methods like monitors(), statusPages(), and checkSummary() are the most commonly used.Monitor, StatusPage, CheckSummary) are pre-loaded with type-safe properties and helper methods (e.g., checkResult()->isUp()).// 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";
}
monitorByUrl() to fetch a monitor by URL, then update/delete as needed:
$monitor = $ohDear->monitorByUrl('https://example.com');
$ohDear->deleteMonitor($monitor->id);
$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',
]);
}
}
$check = $ohDear->requestCheckRun($checkId, [
'User-Agent' => 'CI/CD Pipeline',
]);
$ohDear->snoozeCheck($checkId, 3600); // Snooze for 1 hour
$certHealth = $ohDear->certificateHealth($monitorId);
if (!$certHealth->isHealthy()) {
$daysUntilExpiry = $certHealth->getDaysUntilExpiry();
if ($daysUntilExpiry < 30) {
// Trigger alert or renewal process
}
}
$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(),
]);
}
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());
});
API Rate Limits:
use Symfony\Component\HttpClient\RetryStrategy;
$client = HttpClient::create([
'timeout' => 30,
'retry_on_status' => [429],
'retry_delay' => RetryStrategy::DELAY_MILLISECONDS,
]);
timeoutInSeconds parameter in the OhDear constructor to avoid hanging.Monitor Type Validation:
type field for monitors must match Oh Dear’s supported types (http, ping, tcp). Invalid types throw ValidationException.CheckType enum for check-specific operations to avoid typos.Date/Time Formatting:
'2024-01-01T00:00:00Z'). Use Carbon for consistency:
$now = Carbon::now()->toAtomString();
Team ID Requirement:
team_id. If omitted, the SDK defaults to the authenticated user’s primary team, but explicit IDs are safer for multi-team setups.Pagination:
monitors()) return iterators. To fetch all items, convert to an array:
$monitors = iterator_to_array($ohDear->monitors());
Check IDs vs. Monitor IDs:
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);
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'),
Handle Exceptions Gracefully:
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->
How can I help you explore Laravel packages today?