Skip to content

Writing Handlers

A handler is a PHP file that returns a closure. The closure receives a single argument — an AutomationContext — and runs when any of the automation’s triggers fire.

<?php
return function ($ctx) {
// ... your logic ...
return ['ok' => true];
};

The handler is stored in its own .php file next to the automation object (an external code field), so it’s edited like any code field in the admin but never bloats the collection JSON. It travels with the object through Sync and JumpStart.

$ctx is the only thing a handler receives — pre-wired services plus the trigger payload. No need to reach into a container.

Objects

PropertyWhat it is
$ctx->objectFetcherRead objects — fetchObject($collection, $id)
$ctx->objectSaverCreate objects — saveObject($collection, $data)
$ctx->objectUpdaterUpdate objects — updateObject($collection, $id, $data)
$ctx->objectRemoverDelete objects — deleteObject($collection, $id)
$ctx->objectClonerDuplicate an object — cloneObject($from, $to)
$ctx->propertyIncrementerAtomic counters — incrementProperty($collection, $id, $property, $amount = 1) / decrementProperty(...)

Deck items (cards/repeaters inside an object)

PropertyWhat it is
$ctx->deckItemSaverAdd a deck item — saveDeckItem($collection, $objectId, $property, $itemId, $itemData)
$ctx->deckItemUpdaterUpdate a deck item — updateDeckItem(...)
$ctx->deckItemRemoverRemove a deck item — removeDeckItem($collection, $objectId, $property, $itemId)
$ctx->deckItemFetcherRead deck items — fetchDeckItem(...), fetchAllDeckItems($collection, $objectId, $property)

Querying

PropertyWhat it is
$ctx->indexReaderRead a collection index — fetchIndex($collection) (returns a filterable collection)
$ctx->indexSearcherFull-text-ish search — search($collection, $query), searchByProperty($collection, $property, $query)
$ctx->indexQueryServiceStructured query (filter/sort/paginate) — query($collection, $params)
$ctx->indexBuilderRebuild an index after batch writes — buildIndex($collection)

Collections & schemas

PropertyWhat it is
$ctx->collectionFetcherInspect a collection — fetchCollection($id), collectionExists($id)
$ctx->schemaFetcherInspect a schema — fetchSchemaForCollection($collection), schemaExists($id)

Files & images

PropertyWhat it is
$ctx->fileSaverStore a file into a file field — save(...)
$ctx->imageSaverStore/process an image into an image field — save(...)

Import & sync

PropertyWhat it is
$ctx->csvImporterImport a CSV — import($collection, $file, $updateObject = false)
$ctx->jsonImporterImport JSON — import($collection, $file, $updateObject = false)
$ctx->rssImporterIngest an RSS feed — import($feedUrl, $collection, $options = [])
$ctx->syncServicePush/pull to another T3 install — push(...), pull(...)

Mail, config & run payload

PropertyWhat it is
$ctx->mailerSend a Mailer email — sendEmail($mailerId, $data)
$ctx->httpCall a service whose URL you wrote (an API, a webhook) — request($method, $url, $options) returns statusCode and body. See below
$ctx->publicHttpGET a URL someone else typed — get($url, $options) returns statusCode and body. Public addresses only (see below)
$ctx->configCore configuration
$ctx->loggerPSR-3 logger writing to jobs.log (channel automations)
$ctx->triggerThe trigger row that fired this run (e.g. $ctx->trigger['type'])
$ctx->argsCaller inputs — webhook query + body, or manual Run now args
$ctx->eventEvent payload (collection, id) — event triggers only
$ctx->requestThe PSR-7 request — webhook triggers only

$ctx->request and $ctx->event are null for schedule runs.

Use $ctx->http for a URL you wrote yourself in the handler or in config: a mailing-list API, a payment provider, a Slack webhook, a service on your own network. Use $ctx->publicHttp (below) for a URL that came from content. Don’t create your own Guzzle or curl client: $ctx->http is the one core uses, and tests replace it so a handler under test never reaches the network.

return function ($ctx) {
$sendy = $ctx->config->automations['secrets']['sendy'] ?? [];
$user = $ctx->objectFetcher->fetchObject($ctx->event['collection'], $ctx->event['id']);
try {
$response = $ctx->http->request('POST', $sendy['url'] . '/subscribe', [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'body' => http_build_query([
'api_key' => $sendy['apiKey'],
'list' => $sendy['list'],
'email' => $user['email'],
'boolean' => 'true',
]),
'timeout' => 15,
]);
} catch (\RuntimeException $e) {
throw new \RuntimeException('Sendy is unreachable: ' . $e->getMessage());
}
return ['status' => $response->statusCode, 'body' => $response->body];
};

Options: headers (name => value), body (a string: encode JSON with json_encode(), a form with http_build_query()), timeout and connect_timeout (seconds), follow_redirects (false by default, true or a number), verify_ssl (default true), user_agent, max_bytes. A 4xx or 5xx answer is returned, not thrown: check $response->isSuccess(). A connection failure throws RuntimeException. $response->json() decodes a JSON body.

Don’t write a key into the handler. Handlers live in tcms-data, which travels with sync and JumpStart and is often editable in the admin. Put keys in config/tcms.php, under automations.secrets, and read them from $ctx->config:

config/tcms.php
return [
'automations' => [
'secrets' => [
'sendy' => [
'url' => 'https://newsletter.example.com',
'list' => 'aBc123',
'apiKey' => getenv('SENDY_API_KEY') ?: '',
],
],
],
];

config/tcms.php is PHP, so the value can come from the server’s environment (getenv()) or from a file you keep out of git (require __DIR__ . '/secrets.php'). Core does not read .env files. Core never uses the secrets block itself, and the admin’s server check hides every value in it.

When the URL comes from content (a member’s website, a feed someone added, a link in a form), fetch it with $ctx->publicHttp, not curl or Guzzle directly. A URL like that can point at your own server: http://localhost/, a private network address, or the cloud metadata service at 169.254.169.254. publicHttp refuses all of them:

  • The host must resolve only to public addresses, and the request connects to the address that was checked, so DNS cannot be switched between the check and the request.
  • Redirects are followed one at a time, and each one is checked the same way.
  • Only http and https, with no username or password in the URL.
  • A 10 second timeout, and the body is read up to 2 MB; the rest is dropped.
return function ($ctx) {
try {
$response = $ctx->publicHttp->get($url, ['timeout' => 8, 'max_bytes' => 1_000_000]);
} catch (\RuntimeException $e) {
return ['unreachable' => $e->getMessage()]; // refused, or the site is down
}
if (!$response->isSuccess()) {
return ['status' => $response->statusCode];
}
// $response->body is the page
};

Options: timeout (seconds), max_bytes, max_redirects (default 3), user_agent and headers (name => value).

<?php
return function ($ctx) {
$posts = $ctx->indexReader->fetchIndex('blog')->objects
->where('draft', false)
->take(5);
$ctx->mailer->sendEmail('weekly-digest', ['posts' => $posts->all()]);
$ctx->logger->info('weekly digest sent', ['count' => $posts->count()]);
return ['sent' => $posts->count()];
};
  • Return value — whatever the closure returns is recorded on the run record and, for a synchronous webhook, becomes the HTTP response body. Return arrays/scalars (JSON-encodable).
  • Throwing marks the run failed. In development the error surfaces loudly; in production it’s contained, optionally emailed via the automation’s error mailer, and counts toward auto-disable.

When you save a handler, the editor scans it for high-risk calls — exec, shell_exec, system, passthru, proc_open, eval, backticks, base64_decode, remote file_get_contents, and similar — and shows a non-blocking advisory listing what it found. It’s a heads-up, not a block: many legitimate handlers use these. Review before relying on a handler that reaches for them.