personyze / personyze
Server-side personalization and A/B testing with Personyze. One endpoint, no runtime dependencies.
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
Requires (Dev)
- nyholm/psr7: ^1.8
- phpunit/phpunit: ^10.5
- psr/http-server-middleware: ^1.0
- symfony/http-foundation: ^6.4 || ^7.0
Suggests
- ext-apcu: Page keeps action content and the tag snippet in APCu, shared by every request of the pool; without it, in private files in the temp directory
- psr/http-server-middleware: For Personyze\Framework\Psr15Middleware
Provides
None
Conflicts
None
Replaces
None
README
Server-side personalization and A/B testing. Your server asks "what should this user see?" and renders the answer itself — no client-side flash of default content, nothing for an ad blocker to intercept, and it works for things that are not web pages at all: an API response, a price, a ranking, a kiosk, an email pipeline.
Requires PHP 8.1+, ext-curl and ext-json. No other dependencies — no Guzzle, no PSR-18
adapter, nothing that can conflict with the copy already in your WordPress or Magento install.
APCu is used when it is there.
composer require personyze/personyze
A web page, in one call
$page = Personyze\Page::start ( new Personyze\Client(getenv('PERSONYZE_API_KEY')), ['user_id' => $currentUser?->id] // null for a guest );
Call it before any output. The page then goes out with your campaigns' content in its placeholders, exactly where the browser tag would have put it. What happens:
- The visitor. Your user id when you give one; otherwise the anonymous id this browser already
has (cookie
_pz_uid, or the tag's own withtracker), or a new one — see Visitor ids. - The decision is asked as the request arrives, for the page's own address — what the tag would report, so URL targeting and page groups work as on a tagged page — and the page renders while Personyze answers. Only a browser asking for a page (a GET that accepts HTML) is decided.
- The content goes in when the page is complete. Each action's HTML is put into its
placeholder by the tag's own rules: inside, before, after or in place of the element,
units_count_max,placeholder_order, the style overrides. The page is never re-serialized — every byte outside a filled placeholder stays as you wrote it. executedis reported for you, for each placed action, after the page has gone out.
Anything can branch on the decision while the page renders:
if ($page->decisions()->has(88)) // waits for the answer, once { $shipping = freeShippingOver(50); }
With the Personyze tag on the page
Some things only a browser can do: popups and overlays, recommendation widgets (templates), click
tracking. Add 'tracker' => true and the page also carries the tag — and the visit is handed
over to it: the server logs and decides the page view as the tag's own would be (real address,
referrer, user agent and IP), and the tag adopts that answer instead of logging the page again.
One page view, not two; the units the server placed are adopted where they stand, templates
included; popups and overlays are built by the tag from the same decision; executed is reported
by the tag. Remove the snippet you pasted (or the plugin that adds it) when you turn this on — the
page brings its own.
The tag runs only on your account's listed domains, so on localhost the handoff is in the page
but nothing takes it.
What is placed, and what is not
Without the tag, some actions cannot be rendered on a server and are skipped, never
approximated: templates ($class elements, ontplready, client-side ${...} substitution —
recommendation widgets are like this), actions with no placeholder (popups, overlays),
placeholders written in the tag's own selector extensions or picked visually, and form fields or
table rows as placeholders. Pass on_inject to see what went where and why the rest did not:
'on_inject' => function (array $report) { // ['injected' => [['actionId' => 241, 'placeholderId' => 636], ...], // 'skipped' => [['actionId' => 246, 'reason' => 'no placeholder: a popup or overlay, ...'], ...]] },
Page options
| Option | Default | |
|---|---|---|
user_id |
anonymous | Your id for this visitor, when you know it. Without it the visitor is Personyze's anonymous one ($page->userId() is a Personyze\VisitorId). |
document |
the page's address | The decision point: a string, a Closure returning one, or false for none. |
context |
from the request | Request fields over what the request says (Visitor::context()): first language, device type. |
inject |
true |
Put the content into the page. |
tracker |
false |
Put the Personyze tag on the page and hand the visit over to it. |
session_store |
the client's | Where the session lives. |
cookie |
The _pz_uid cookie, and _pz_new beside it: secure (default: the request's own scheme, proxies included), samesite, path, domain, ttl, and writer — function (string $name, string $value, array $options) in place of setcookie(). |
|
cache |
APCu, else files | Where action content and the snippet are kept between requests (Personyze\Cache). |
ip |
REMOTE_ADDR |
The visitor's address when PHP's is a proxy's (tracker only). Take it from whatever honours your proxy configuration, never from a raw X-Forwarded-For. |
on_inject |
function (array $report, Page $page). |
|
buffer |
true |
Hold the page in an output buffer. false for a framework that hands its response body to $page->transform($html) itself. |
Page is for PHP that serves one request per process lifetime — PHP-FPM, mod_php, the built-in
server — including WordPress, Laravel and Symfony running that way. A long-running server
(Swoole, RoadRunner, Laravel Octane) shares $_SERVER and the output buffer across requests: use
Client there.
WordPress, Laravel, PSR-15
// wp-content/mu-plugins/personyze.php require __DIR__.'/personyze/vendor/autoload.php'; Personyze\Framework\WordPress::start(new Personyze\Client(PERSONYZE_API_KEY), ['tracker' => true]); // in a theme: Personyze\Page::current()?->decisions()->has(88)
// Laravel: a web middleware; the logged-in user is the visitor $middleware->web(append: [Personyze\Framework\LaravelMiddleware::class]); // in a controller: $request->attributes->get('personyze')->decisions()
// Slim, Mezzio, any PSR-15 stack (needs psr/http-server-middleware and a PSR-17 stream factory) $app->add(new Personyze\Framework\Psr15Middleware($client, $psr17Factory, ['tracker' => true]));
The WordPress hook skips the admin, AJAX, REST, cron, feeds and robots.txt. The two middlewares
personalize a 200 text/html body held in memory and leave everything else alone.
Any other decision point: Client
$personyze = new Personyze\Client('YOUR_API_KEY'); $decisions = $personyze->decide(123456, 'urn:personyze:doc:checkout'); if ($decisions->has(88)) { renderFreeShippingBanner(); $personyze->reportExecuted(123456, 88); // without this, action 88 looks like it never ran }
Get your API key from Settings → API key in the panel, or see the docs.
If you don't report executed, your variant looks like it has no traffic
This is the one step that is easy to forget and impossible to notice from the outside. (Page
does it for you.)
Personyze scores an A/B test as conversions over sessions in which the action ran.
reportExecuted() is what supplies the denominator. Skip it and the arm reports zero sessions,
zero conversions, and no error anywhere — the test simply never concludes, and the panel shows a
variation that appears to have received no traffic at all. There is no retroactive fix: the
sessions are gone.
A report is no reason to make the visitor wait, though. later() sends it once the page is out —
after fastcgi_finish_request() hands the page to the browser — together with anything else
queued for that user, in one request:
$personyze->later($userId, [['action status', 88, 'executed']]);
Running a server-side A/B test
- Create the test in the panel. Personyze assigns each user to an arm and keeps them there. Do not implement the split yourself — if you do, the two systems disagree about who is in which arm and every number downstream becomes fiction.
- Give each arm an action. For a purely server-side test the action needs no visual content: the id alone tells your code which branch to take.
- Ask at the decision point, branch on the id, and report what you did.
$decisions = $personyze->decide ( $userId, 'urn:personyze:doc:checkout', ['commands' => [['Product Added to cart', 'SKU-8891']]] // one round trip: the event and the decision ); $arm = $decisions->firstOf([88, 89]); switch ($arm) { case 88: { $shipping = freeShippingOver(50); break; } case 89: { $shipping = freeShippingOver(80); break; } default: // control group, or the call failed { $shipping = standardShipping(); } } if ($arm) { $personyze->later($userId, [['action status', $arm, 'executed']]); } // ... later, when the user checks out. Which call you make depends on how the test is scored. $personyze->reportPurchase($userId, 'SKU-8891', ['action_id' => 88, 'quantity' => 1]);
Read the verdict whenever you like — it never promotes anything:
$verdict = $personyze->verdict(1878); // the campaign id echo $verdict['has_winner'] ? "winner: {$verdict['winner_actiongroup_id']}\n" : "not yet: {$verdict['message']}\n";
Report the signal your winner criterion actually measures
| Criterion | Send |
|---|---|
| Clicks | $personyze->reportEngaged($userId, 88) |
| Products purchased | $personyze->reportPurchase($userId, 'SKU-1', ['action_id' => 88]) |
| Goal event | whatever fires that goal in your account, via track() |
| Bounce rate | nothing extra — it follows from decide() |
reportEngaged() drives Clicks and only Clicks. It is not a generic "conversion" method: on
a purchase-scored test it will not move the numbers. A purchase without its action_id is
recorded but credits no arm. In every case also report executed, or the arm has no denominator.
A decision that renders while you work
decideAsync() sends the request now and collects the answer later — what Page does with every
page:
$pending = $personyze->decideAsync($userId, 'urn:personyze:doc:home'); // ... build the page; Personyze is answering meanwhile ... $decisions = $pending->wait();
The budget counts from the call. An answer that arrived while you worked is collected however long
that took; one still missing when the budget is spent is given up on, as with decide().
Sessions
The session_id is the conversation. Losing it starts a new session and can re-bucket the
user into a different A/B arm. This SDK loads it before every call and stores whatever comes
back, through a SessionStore:
| Store | Use it for |
|---|---|
CookieSessionStore (default) |
Web requests. The browser holds the session, your servers stay stateless. |
ArraySessionStore |
CLI scripts, queue workers, tests. Single process only. |
Anything else is a dozen lines:
class RedisSessionStore implements Personyze\SessionStore { public function load(string $key): ?string { return $this->redis->get("personyze:$key") ?: null; } public function save(string $key, string $sessionId): void { $this->redis->setex("personyze:$key", 2592000, $sessionId); } }
A store that fails — Redis is down — makes the call fail open like an outage: an empty decision,
and on_failure. A cookie can only be set before the page starts going out: a decision made
later (in a template, past the first few KB of output) still answers, but on_failure gets a
SessionStoreException naming the file and line where output started — without it, every such
page would silently open a new session.
A stored session that has gone stale is not a problem either. Before each request the SDK reads
the session's start time — field 0 of the session string — and asks for a new session only when
there is nothing stored, when what is stored is unreadable, or when it has passed the server's 90
minute timeout. So an expired or corrupt session heals itself instead of erroring, and a live one
is left alone. (new_session: true next to a valid session does not mean "recover if stale" — it
starts a new session, and an SDK that sent it on every request would re-bucket the visitor on
every request.)
A session also names its visitor (field 1), and the server takes the visitor from the session,
not from user_id or pz_visitor_id. So a stored session of someone else — a cookie two users of
one browser shared, the guest who then logged in — is not sent: this user starts a session of their
own. Visitors are compared exactly, 64-bit ones included.
Visitor ids (64-bit, protocol 2)
Every call names its visitor with $userId, which is one of two things:
- Your own id for the visitor — a login: an
intor astring, sent asuser_id. It should be an integer you control: the server coerces it to a 32-bit integer, so a string id is hashed and two different strings can collide. This is exactly as it always was, so a logged-in user keeps their profile, history and A/B arms across versions of this SDK. - Personyze's own id for a visitor you do not know — a guest: a
Personyze\VisitorId, sent aspz_visitor_id, as text, exactly, at any width.Personyze\Visitor::id()gives you one kept in the_pz_uidcookie (and the request's language and device type arePersonyze\Visitor::context()).
$visitor = Personyze\Visitor::id($currentUser?->id); // your id when you have one, else a VisitorId $decisions = $personyze->decide($visitor, 'urn:personyze:doc:home'); $personyze->later($visitor, [['action status', 88, 'executed']]);
An empty $userId is refused: the server would make every guest one visitor.
Why two kinds. Personyze's visitor ids are 64-bit numbers on an account that mints them (the
browser tag mints them there too). Before 1.2.0 this SDK sent its anonymous ids as user_id, the
field for yours, which the server coerces to 32 bits — so a 64-bit visitor could not pass through: its
digits became a hash, somebody else, and a tag visitor handed to the server with tracker was split
in two. Since 1.2.0 the SDK speaks protocol 2 of the endpoint, which names the two apart, and reads
every visitor id — the session's, the tag cookie's, the answer's — as text, never through a float.
New visitors, and the answer's id. A new anonymous visitor is minted here and sent as new
(pz_visitor_new) until an answer names it — across requests too: the _pz_new=1 cookie beside
_pz_uid keeps it new until then, so a first call that timed out is sent as new again, and the
server gives it the same id it may already have logged. The server decides the width: where the
account mints 64-bit ids it gives a new 32-bit visitor a 64-bit id, and the answer says which id the
visitor has now. The SDK takes it — the VisitorId you passed holds the new id afterwards, and the
cookies are rewritten — in the same step as it saves the session that came with it, under the new
id. While a new visitor's decision is in flight (decideAsync(), Page), every other call for it
waits for that answer first. A PHP process remembers nothing between requests, so a new visitor is
minted at 32 bits unless the width is known: Client::idBits() is the last answer's, and Page
keeps it per account in its cache (APCu, shared by the pool), so after the pool's first new visitor
the next ones are minted at 64 bits at once.
Report after the first decision. A report sent without a Navigate for a new visitor the server
gives another id is not logged: the new visitor has no page view yet. The server answers 200 all
the same; the SDK tells it by its signs, returns failed Decisions and hands on_failure an
EventsNotLoggedException. decide() first — Page does — and report after.
If you keep anonymous ids somewhere other than the cookie — a mobile backend's own store, say — keep
the id the VisitorId holds after the call, and whether it is still new (or hook
$visitor->onChange(), called before the session is saved):
$visitor = Personyze\VisitorId::from($device->personyzeId ?? '', (bool)$device->personyzeNew) ?? Personyze\VisitorId::mint($personyze->idBits()); $decisions = $personyze->decide($visitor, 'urn:personyze:doc:home'); $device->update(['personyzeId' => $visitor->id(), 'personyzeNew' => $visitor->isNew()]);
The server first. Protocol 2 needs a Personyze server that speaks it; an older one answers each anonymous visitor's request as a new random visitor. As a safety net the SDK then takes the visitor from the answer's session, which keeps the visitor and its session from the second call on.
Downgrading splits visitors. Going back from 1.2.0 to an older version of this SDK loses every 64-bit visitor it holds: versions before 1.2.0 read ten digits at most, so each such visitor becomes a new one, and a tag visitor is split from the page it lands on.
Upgrading from 1.1
Your own ids (int/string) are sent and keyed exactly as before. What changed is the anonymous
visitor, which is now an object, and the helpers that return visitor ids, which are now text:
Visitor::id()returnsint|string|VisitorId— aVisitorIdfor a guest — and takes a third argument,$bits.Visitor::stored()andVisitor::anonymousId()return aVisitorId, andPage::userId()may be one. It goes anywhere a$userIdwent, and(string)$visitoris the id;(int)Visitor::id()now warns (an object to int) and gives 1.Session::visitor()andSession::visitorOf()return the visitor as a?string:Session::visitor($s) === 123is false now — compare with'123'.Handoff::chooseSession()takes aVisitorIdas well, andTagSessionStoretakes the page's visitor as a third argument.Visitor::stored()takes every id a visitor is minted — 64-bit ones and negative 32-bit ones — but none of the server's own ranges, below 500,000,000 or in [2^31, 2^62).- The
_pz_uidcookie is no longerHttpOnly, and_pz_newbeside it never is: a script on the page may have to rewrite both, and the Node and Python SDKs write them alike, so a site moving between them on one domain is never stuck with a cookie it cannot rewrite. Its other attributes are as before; the session cookie (personyze_session) is unchanged. - A
Clientcannot be serialized:serialize($client)throws (Serialization of 'WeakMap' is not allowed) where 1.1 returned a string. That string was never a working client: the API key does not travel with one, so a 1.1 client unserialized in another process sent its requests with no key. Make aClientfrom your key in each process instead.
Fail open
A personalization call must never take down the page it personalizes.
- Default timeout 1000 ms for the whole call, retry included —
timeout_msto change it. - At most one retry, only for a connection error or a 5xx, and only if budget remains.
- A timeout, a connection error, a 5xx, a paused account (429), a session store that is down, and
"no actions matched" are the same outcome: an empty
Decisions, and you render your default.decide()does not throw for these.$decisions->failed()tells them apart, if you care. - Text from the visitor that is not valid UTF-8 — a Latin-1 URL, an odd header — is replaced, not refused.
on_failurefires for every failure, including from the reports — fire-and-forget, but never silently dropped.
Reads fail open, writes fail loud. A bad API key or malformed input is a bug in your
integration, so 400 and 401 throw even from decide(). Pass 'raise_config_errors' => false
if you would rather they fail open too — and then watch on_failure. Page::start() never
throws for its own decision; the error reaches on_failure, and $page->decisions() throws it.
verdict(), actions(), placeholders() and trackerCode() throw on any failure: they are
reads with nothing to fail open to.
Calls are cheap to repeat: connections are kept and shared (on PHP 8.5 across requests, too), and answers come compressed.
Options
| Option | Default | |
|---|---|---|
base_url |
https://app.personyze.com |
Must be https://. /rest is also served on api.personyze.com, counter*.personyze.com and segment.personyze.com — but not on personyze.com. |
timeout_ms |
1000 |
Budget for the whole call, retries included. |
retries |
1 |
0 or 1; anything higher is clamped, because the endpoint is not idempotent. |
session_store |
CookieSessionStore |
|
on_failure |
none | function (Throwable $error, string $operation). |
transport |
CurlTransport |
Implement Personyze\Transport (and AsyncTransport for decideAsync()) to use your own HTTP stack. |
defaults |
[] |
Fields merged into every request: languages, time_zone, screen, os, platform, device_type. |
force_new_session |
false |
Start a new session on every call. Normally leave it alone. |
raise_config_errors |
true |
API
$userId below is your own id (int/string, sent as user_id) or a Personyze\VisitorId (sent as
pz_visitor_id) — see Visitor ids.
Client |
|
|---|---|
decide($userId, $document, $context = []) |
One round trip with a Navigate. Returns Decisions. Fails open. |
decideAsync($userId, $document, $context = []) |
The same, collected later with ->wait(). |
reportExecuted($userId, $actionId) |
You rendered it. Required for scoring. |
reportEngaged($userId, $actionId) |
The user clicked it — the Clicks criterion. |
reportClosed($userId, $actionId) |
The user dismissed it. |
reportPurchase($userId, $sku, ['action_id' => , 'quantity' => ]) |
The Products purchased criterion. |
setProfile($userId, $fields) |
Fields on the user's profile. |
track($userId, $commands) |
Arbitrary commands, no Navigate. The escape hatch. |
later($userId, $commands) / flush() |
Send once the page is out / now. |
verdict($conditionId) |
GET /rest/ab_test — who is winning. Throws on failure. |
actions($ids), placeholders($ids), trackerCode() |
Action content, placeholder definitions, the tag snippet. Throw on failure. |
withSessionStore($store) |
The same client, keeping sessions elsewhere. |
idBits() |
The width the account mints new visitor ids at, as the last answer said: 32 or 64 (32 until one has). |
Decisions gives you has($actionId), firstOf($actionIds), dataFor($actionId), actions(),
actionIds(), conditions(), conditionIds(), dismissActions(), dismissConditions(),
sessionId(), cacheVersion(), visitorId() (the visitor the call was logged under, as text),
idBits(), handoff(), isEmpty(), failed(), error() and raw(). The response is passed
through unaltered, so an example from the wiki works against raw() without translation.
Page gives you decisions(), decide($document), the reports bound to its visitor,
later($commands), userId() (your id, or the anonymous visitor's VisitorId), document(),
client(), report(), transform($html) and Page::current().
Personyze\VisitorId |
|
|---|---|
Visitor::id($known = null, $cookie = [], $bits = 32) |
$known when given, else this browser's anonymous visitor (cookie _pz_uid), else a new one. |
VisitorId::mint($bits = 32) |
A new visitor, sent as new until an answer names it. $bits: $client->idBits(). |
VisitorId::from($id, $new = false) |
One you kept (and whether it is still new), or null when $id is not a visitor id (up to 19 digits and a sign). |
id(), (string), isNew() |
The canonical decimal; whether it was minted here and not yet answered. |
onChange(fn(VisitorId $v, string $previous) => ...) |
Called when an answer names another id for the visitor, or names it at last, before its session is saved. |
Exceptions all extend Personyze\PersonyzeException: AuthException (401),
BadRequestException (400 and other 4xx), TransportException (timeout, connection error, 5xx,
429, unparseable body), SessionStoreException, and EventsNotLoggedException (never thrown: handed
to on_failure for a report the server did not log, above). The API key never appears in an exception
message, in any string representation of the client — print_r(), var_dump() included — or,
on PHP 8.2+, in an exception's trace, which is what error trackers record.
Notes
- Do not cache decisions across users, or across
Navigates for the same user.cacheVersion()is for caching action content, whichPagedoes. - Do not bucket users yourself. Personyze owns the assignment.
- A user who arrives through your server one day and through the browser tag the next stays in the same arm, provided both identify them the same way.
Tests
composer install
composer test # no network: the transport is faked
PERSONYZE_API_KEY=... composer test-conformance # the golden path, against the real endpoint
for-developer/phpsdk-test in the Personyze repository is a test page for everything above,
with a live check of every feature and a browser check with the real tag.
Links
MIT licensed.