PHP code example of confish / sdk

1. Go to this page and download the library: Download confish/sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

confish / sdk example snippets


use Confish\Confish;

$client = new Confish(
    envId: getenv('CONFISH_ENV_ID'),
    apiKey: getenv('CONFISH_API_KEY'),
);

$config = $client->config->fetch();
echo $config['site_name'];

/** @var array{site_name: string, max_upload_mb: int, maintenance_mode: bool} $config */
$config = $client->config->fetch();

// GET /c/{env_id}
$config = $client->config->fetch();

// PATCH — only listed fields change
$client->config->update(['maintenance_mode' => true]);

// PUT — replaces everything; omitted fields reset to defaults
$client->config->replace([
    'site_name'        => 'My App',
    'max_upload_mb'    => 50,
    'maintenance_mode' => false,
]);

$jobs = $client->feed('jobs');

// PUT — create-or-replace ("upsert") by external ID; returns a FeedItem
$jobs->set('sitemap-crawl', ['status' => 'running', 'urls' => 1423], ttl: 86400);

// The environment's live items, newest first — list<FeedItem>
foreach ($jobs->list() as $item) {
    echo "{$item->externalId}: {$item->data['status']}\n";
}

// Idempotent — deleting an item that is already gone succeeds
$jobs->delete('sitemap-crawl');

$result = $jobs->replace([
    ['external_id' => 'sitemap-crawl', 'data' => ['status' => 'running'], 'ttl' => 86400],
    ['external_id' => 'image-crawl',   'data' => ['status' => 'queued']],
]);
echo "{$result->created} created, {$result->updated} updated, {$result->deleted} deleted";

use Confish\LogLevel;

$client->logs->info('Worker started', ['region' => 'eu-west-1']);
$client->logs->error('Job failed', ['job_id' => 'abc']);

// Or with an explicit level:
$logId = $client->logs->write(LogLevel::Critical, 'system down', ['code' => 503]);

$ids = $client->logs->writeBatch([
    ['level' => LogLevel::Info, 'message' => 'Crawl started', 'context' => ['urls' => 1423]],
    ['level' => 'error', 'message' => 'Import failed', 'timestamp' => '2026-07-12T09:58:12+00:00'],
]);

use Confish\MonologHandler;
use Monolog\Level;
use Monolog\Logger;

$logger = new Logger('crawler');
$logger->pushHandler(new MonologHandler($client, level: Level::Info));

$logger->info('Sitemap crawl started', ['urls' => 1423]);
$logger->error('Import failed', ['exception' => $e]);

$handler = new MonologHandler($client, onError: function (Throwable $e, int $dropped): void {
    error_log("confish: dropped $dropped log entries: {$e->getMessage()}");
});

use Confish\PsrLogger;

$logger = new PsrLogger($client);
$logger->warning('Certificate expires soon', ['domain' => 'example.com', 'days_left' => 7]);

// app/Providers/AppServiceProvider.php
use Confish\Confish;

public function register(): void
{
    $this->app->singleton(Confish::class, fn () => new Confish(
        envId: config('services.confish.env_id'),
        apiKey: config('services.confish.api_key'),
    ));
}

// config/logging.php
'channels' => [
    // ...
    'confish' => [
        'driver'  => 'monolog',
        'handler' => Confish\MonologHandler::class,
        'level'   => env('LOG_LEVEL', 'info'),
        'handler_with' => [
            'flushAt' => 50,
        ],
    ],
],

use Confish\Action;
use Confish\ActionUpdater;
use Confish\Confish;
use Confish\Exception\SkipActionException;

$client = new Confish(envId: '...', apiKey: '...');

// Wire SIGTERM/SIGINT to a stop flag (T,  function () use (&$shouldStop) { $shouldStop = true; });
}

$client->actions->consume(
    handler: function (Action $action, ActionUpdater $u): ?array {
        if ($action->type === 'rebuild_index') {
            $u->progress('Rebuilding search index', ['params' => $action->params]);
            // ... do work ...
            return ['documents_indexed' => 15230, 'duration_ms' => 8412];
        }
        throw new RuntimeException("unknown action type: {$action->type}");
    },
    pollInterval: 15.0,    // base — defaults to 15s
    maxPollInterval: 60.0, // adaptive backoff cap
    shouldStop: fn (): bool => $shouldStop,
    onError: fn (Throwable $e, Action $a) => error_log("action {$a->id}: {$e->getMessage()}"),
);

$actions = $client->actions->list();
$client->actions->ack('action_id');
$client->actions->progress('action_id', 'Crawling sitemap 2 of 5', ['step' => 2]);
$client->actions->complete('action_id', ['pages_crawled' => 1423]);
$client->actions->fail('action_id', ['error' => 'timeout']);

use Confish\Exception\WebhookVerificationException;
use Confish\Webhook;

// Inside a controller / route handler:
$body      = file_get_contents('php://input');         // raw, unparsed
$signature = $_SERVER['HTTP_X_CONFISH_SIGNATURE'] ?? null;

try {
    $payload = Webhook::verify(
        body: $body,
        signature: $signature,
        secret: getenv('CONFISH_WEBHOOK_SECRET'),
    );
} catch (WebhookVerificationException $e) {
    http_response_code(401);
    exit('Invalid webhook: '.$e->getMessage());
}

// $payload->event, $payload->environment['env_id'], $payload->changes, $payload->values ...

use Confish\Exception\WebhookVerificationException;
use Confish\Webhook;
use Illuminate\Http\Request;

Route::post('/webhook', function (Request $request) {
    try {
        $payload = Webhook::verify(
            body: $request->getContent(),
            signature: $request->header('X-Confish-Signature'),
            secret: config('services.confish.webhook_secret'),
        );
    } catch (WebhookVerificationException) {
        abort(401);
    }

    // handle $payload->event ...
    return response()->noContent();
});

use Confish\Exception\{
    AuthException,
    ConfishException,
    ConflictException,
    ForbiddenException,
    NetworkException,
    NotFoundException,
    RateLimitException,
    ServerException,
    ValidationException,
};

try {
    $client->config->fetch();
} catch (RateLimitException $e) {
    sleep($e->retryAfter ?? 1);
} catch (ValidationException $e) {
    foreach ($e->errors as $field => $messages) {
        echo "$field: ".implode(', ', $messages);
    }
} catch (ConfishException $e) {
    echo "HTTP {$e->statusCode}: {$e->getMessage()}";
}

use GuzzleHttp\Client as GuzzleClient;

$client = new Confish(
    envId: 'a1b2c3d4e5f6',
    apiKey: 'confish_sk_...',
    baseUrl: Confish::DEFAULT_BASE_URL, // override for self-hosted
    httpClient: new GuzzleClient(['timeout' => 10.0]), // inject your own
    userAgent: 'my-app/1.0',
    maxRetries: 2,
    maxRetryDelay: 30.0,
);