# PHP SDK

Use the `cronitor/cronitor-php` Composer package to report job runs, heartbeats, and metrics to Cronitor.

## Install

```bash
composer require cronitor/cronitor-php
```

## Configure

Set the `CRONITOR_API_KEY` environment variable to your SDK Integration key. Copy the key from Settings → API Keys at https://cronitor.io/app/settings/api. Keep the key in the environment or a secret store of the runtime. Do not commit it.

The `Cronitor\Client` constructor needs an API key argument. Give it the value of the environment variable:

```php
<?php
require 'vendor/autoload.php';

$cronitor = new Cronitor\Client(getenv('CRONITOR_API_KEY'));
```

## Monitor a job

Give the work of the job to `$cronitor->job` as a closure or an invokable object:

```php
$cronitor->job('send-invoices', function () {
    (new SendInvoices())->run();
});
```

- Before the closure starts, the SDK sends a `run` event.
- When the closure returns, the SDK sends a `complete` event. `$cronitor->job` gives the return value of the closure.
- When the closure throws an `Exception`, the SDK sends a `fail` event with the exception message. Then it throws the exception again.
- Cronitor calculates the `duration` from the `run` event and the `complete` or `fail` event.
- The events go to the monitor with the key `send-invoices`. If no monitor has this key, Cronitor creates one on the first event.

For Laravel scheduled tasks and queue jobs, use [cronitor-laravel](https://github.com/cronitorio/cronitor-laravel).

To send the events yourself, use a monitor:

```php
$monitor = $cronitor->monitor('send-invoices');
$monitor->ping(['state' => 'run']);
$monitor->ping(['state' => 'complete']); // or 'state' => 'fail'
```

## Send a heartbeat

Send a ping each time the process completes a unit of useful work:

```php
$monitor = $cronitor->monitor('queue-worker');
$monitor->ping(['message' => 'Alive!']);
```

To attach metrics, give a `metrics` array. The SDK sends each item as `metric=name:value`:

```php
$monitor->ping(['metrics' => ['count' => 100, 'error_count' => 3]]);
```

If you only want to record custom metrics, use a heartbeat monitor. See [Custom Metrics](https://cronitor.io/docs/custom-metrics.md).

## Verify

After one real run, check the state of the monitor. A successful telemetry response shows only that Cronitor received the request. It does not show that Cronitor stored the event or matched it to a monitor.

With the [MCP server](https://cronitor.io/docs/mcp-server.md):

```text
get_status({"key": "send-invoices"})
```

With [CronitorCLI](https://cronitor.io/docs/using-cronitor-cli.md):

```bash
cronitor status send-invoices
```

## Reference

- [cronitor-php on GitHub](https://github.com/cronitorio/cronitor-php): the full README, including YAML configuration and the Monitor API.
- [Telemetry API](https://cronitor.io/docs/telemetry-api.md): the events and parameters that the SDK sends.
