PHP API & Hooks
Because Campaign registers with 'autoload' => false, 'singular' => true, unrelated frontend requests pay zero boot overhead. Resolve the module lazily whenever your template, hook, or custom module needs it.
Resolving the Campaign Instance
Section titled “Resolving the Campaign Instance”<?phpdeclare(strict_types=1);
namespace ProcessWire;
use Totoglu\Campaign\Campaign;
// Returns null if Campaign is not installed$campaign = Campaign::instance($this);
// Throws WireException if Campaign is not installed$campaign = Campaign::requireInstance($this);Inside template files (site/templates/*.php), pass $wire instead of $this.
Primary Facade Methods
Section titled “Primary Facade Methods”| Method | Signature / Purpose |
|---|---|
subscribe() |
$campaign->subscribe(string $email, string $listHandleOrId, array $options = []) creates or updates a contact and list subscription (respecting Double Opt-In unless confirm => true). |
confirmDoubleOptIn() |
$campaign->confirmDoubleOptIn(string $token) verifies a confirmation token and activates the subscription. |
unsubscribe() |
$campaign->unsubscribe(string $email, ?string $listHandleOrId = null, string $reason = 'user_request') unsubscribes from one list or globally. |
renderSubscribeForm() |
$campaign->renderSubscribeForm(string $listHandle, array $options = []) returns CSRF + honeypot + rate-limited HTML form markup. |
sendNow() |
$campaign->sendNow(EntryItem $sendout) materializes recipients and queues ProcessSendoutBatchQueue batches immediately. |
scheduleSendout() |
$campaign->scheduleSendout(EntryItem $sendout, string $utcDateTime) sets scheduled_at and moves the sendout to scheduled state. |
sendTest() |
$campaign->sendTest(EntryItem $campaignEntry, array $emails, ?EntryItem $sampleContact = null) sends immediate test messages. |
isDemoMode() |
Returns true when Campaign is running in read-only demo protection mode. |
assertNotDemoMode() |
Throws an exception before destructive or outbound-mail actions when Demo Mode is active. |
fake() |
$campaign->fake() activates FakeCampaignMailer in memory for deterministic automated tests. |
All 16 Sub-Services
Section titled “All 16 Sub-Services”Access lower-level domain services directly from the Campaign facade:
| Accessor | Service Class | Responsibility |
|---|---|---|
$campaign->settings() |
CampaignSettings |
Immutable snapshot of the 23 global settings in campaign-settings. |
$campaign->tables() |
CampaignTables |
Managed SQL schema creation, migration, and cleanup for all 5 tables. |
$campaign->tokens() |
TokenService |
HMAC-SHA256 signing and verification for open, click, view, confirm, unsubscribe, and preference tokens. |
$campaign->rateLimiter() |
CampaignRateLimiter |
Per-IP and per-email throttling for /_campaign/subscribe and public endpoints. |
$campaign->renderer() |
CampaignRenderer |
4-mode rendering, merge variables, relative image absolutization, CSS inlining, UTM and tracking injection. |
$campaign->suppressions() |
SuppressionService |
Global suppression checks, soft-bounce escalation, manual block/unblock. |
$campaign->subscriptions() |
SubscriptionService |
Low-level subscription CRUD, Double Opt-In state machine, role sync orchestration. |
$campaign->transfer() |
TransferService |
CSV import parsing and writeSubscribersCsv() streaming export. |
$campaign->segments() |
SegmentEvaluator |
Evaluates contact, subscription, and engagement rules across 16 operators. |
$campaign->recurrence() |
RecurrenceCalculator |
Computes next UTC run timestamps for daily, weekly, monthly, and custom cron sendouts. |
$campaign->dispatcher() |
CampaignDispatcher |
Audience materialization, batch claiming, WireMail dispatch, retry/backoff. |
$campaign->automations() |
AutomationEngine |
Evaluates the 5 event triggers (list_subscribed, contact_created, user_registered, form_submitted, contact_date_field). |
$campaign->analytics() |
AnalyticsService |
KPI rollups, open/click rates, per-sendout delivery funnels, and link leaderboards. |
$campaign->webhooks() |
WebhookService |
ESP signature verification, payload normalization, and transactional deduplication. |
$campaign->publicHttp() |
PublicHttpService |
Handles all 8 public /_campaign/* URL hook endpoints. |
$campaign->activeMailer() |
WireMail |
Resolves the active WireMail transport (or FakeCampaignMailer when faked). |
All 11 Domain Hookable Methods (Campaign & ProcessCampaign)
Section titled “All 11 Domain Hookable Methods (Campaign & ProcessCampaign)”| Hook | Arguments & Return | Timing | What It Does |
|---|---|---|---|
Campaign::activeMailer |
(?CampaignSettings $settings = null): CampaignMailerInterface |
After | Resolves the outbound mailer transport so high-volume newsletters can use a dedicated SMTP/API mailer. |
Campaign::resolveBlueprint |
(string $type, array $definition): array |
After | Customizes campaign* Entries blueprint fields before registration. |
Campaign::afterSubscribe |
(ContactEntry $contact, MailingListEntry $list, string $source): void |
After | Fires after an active subscription is confirmed (ideal for CRM sync or onboarding logs). |
Campaign::afterUnsubscribe |
(string $contactId, string $listId, bool $allLists, string $source): void |
After | Fires after a single-list or global opt-out completes. |
Campaign::afterRender |
(CampaignEntry $campaign, RenderedEmail $email, array $context = []): RenderedEmail |
After | Inspects or post-processes rendered HTML and plaintext before tracking/dispatch. |
Campaign::beforeSend |
(SendoutEntry $sendout, CampaignEntry $campaign, ?ContactEntry $contact, RenderedEmail $email): RenderedEmail |
After | Adds custom MIME headers, dynamic attachments, or per-recipient overrides right before dispatch. |
Campaign::afterSend |
(SendoutEntry $sendout, CampaignEntry $campaign, ?ContactEntry $contact, DispatchOutcome $outcome): void |
After | Fires after each WireMail::send() attempt with the DispatchOutcome and ESP message ID. |
Campaign::renderBlocksContent |
(string $layoutHandle, array $context = []): string |
After | Overrides how Blocks layouts compile into email-safe table markup. |
Campaign::aiSuggest |
(string $action, array $payload = []): array |
After | Customizes subject-line or copywriting suggestions in the campaign editor. |
Campaign::forwardWebhook |
(string $event, array $payload = []): void |
After | Forwards verified ESP bounce, complaint, open, or click events to external webhooks or warehouses. |
ProcessCampaign::translations |
(): array |
After | Overrides or extends localized UI strings passed into the Setup -> Campaigns React workspace. |
Hook Examples (site/ready.php)
Section titled “Hook Examples (site/ready.php)”<?php
declare(strict_types=1);
namespace ProcessWire;
use Totoglu\Campaign\Domain\DispatchOutcome;use Totoglu\Campaign\Domain\RenderedEmail;use Totoglu\Campaign\Entity\CampaignEntry;use Totoglu\Campaign\Entity\MailingListEntry;use Totoglu\Contacts\Entity\ContactEntry;
// 1. Add a custom MIME header before every newsletter dispatch$wire->addHookAfter('Campaign::beforeSend', function (HookEvent $event): void { $rendered = $event->return; if (!$rendered instanceof RenderedEmail) { return; } $headers = $rendered->headers; $headers['X-Aegean-Region'] = 'Mediterranean'; $event->return = $rendered->withHeaders($headers);});
// 2. React when a subscriber confirms membership on a mailing list$wire->addHookAfter('Campaign::afterSubscribe', function (HookEvent $event): void { /** @var ContactEntry $contact */ $contact = $event->arguments(0); /** @var MailingListEntry $list */ $list = $event->arguments(1); $source = (string) $event->arguments(2); $event->wire()->log->save('campaign-sub', "Contact {$contact->id} joined {$list->handle} via {$source}");});
// 3. Record external telemetry after each message is dispatched$wire->addHookAfter('Campaign::afterSend', function (HookEvent $event): void { /** @var CampaignEntry $campaign */ $campaign = $event->arguments(1); /** @var DispatchOutcome $outcome */ $outcome = $event->arguments(3); if (!$outcome->ok) { $event->wire()->log->save('campaign-errors', "Send failed for {$campaign->id}: {$outcome->error}"); }});Outbound Webhook Payload & HMAC Verification
Section titled “Outbound Webhook Payload & HMAC Verification”When Campaign::forwardWebhook forwards verified ESP events (campaign.delivered, campaign.opened, campaign.clicked, campaign.bounced, campaign.unsubscribed), outbound deliveries include X-Campaign-Signature (sha256=<hex>):
{ "event": "campaign.opened", "timestamp": "2026-06-15T12:30:00Z", "data": { "sendout_id": "0196f8d2-3c1a-7b40-9e12-8a4c5d6e7f01", "contact_id": "0196f8d2-9a0b-7c10-8d33-1b2c3d4e5f02" }}Verify the signature on your receiver with hash_equals('sha256=' . hash_hmac('sha256', $rawBody, $secret), $_SERVER['HTTP_X_CAMPAIGN_SIGNATURE'] ?? '').
Automated Testing with FakeCampaignMailer
Section titled “Automated Testing with FakeCampaignMailer”Call $campaign->fake() in Pest or PHPUnit tests to intercept all outbound mail without touching an external SMTP server. Use isFake(), resetState(), and clearFake() to isolate test cases:
<?phpdeclare(strict_types=1);
namespace ProcessWire;
use Totoglu\Campaign\Campaign;
$campaign = Campaign::requireInstance($wire);$fake = $campaign->fake();
try {
// Inspect captured messages in memory $sent = $fake->sent(); $count = count($sent); $isFaked = $campaign->isFake();
$fake->resetState();} finally { $campaign->clearFake();}