All questions

How do I evaluate a CQL audience condition from my PHP backend?

Asked by rui.tavares on

Rrui.tavares

my PHP service picks what to render based on whether the visitor matches an audience. Right now I fetch a slot for every case and branch on the result, which feels backwards. I would rather ask "does this visitor match X" once and branch on that.

Concrete example of what I want: check whether the visitor is a returning user, or whether they are browsing from Brazil, before deciding the layout. How do I run a CQL evaluation server-side, and what should I watch out for? A short code shape would help.

Was this helpful?

2 answers

DLDevon LaneAccepted answer

Yeah, evaluate is exactly what you want here. You send a CQL condition and get back a boolean, so you branch on that instead of fetching a slot per case.

CQL is English-like and case-insensitive, so both of your examples are close to what you would say out loud:

user is returninglocation's countryName is "br"

The one thing to always do is guard the call with a fallback. If the evaluation fails or times out, you catch it and treat the result as false (or whatever your safe default is) so a hiccup does not break the request:

$isReturning = false;try {    $isReturning = $croct->evaluate('user is returning');} catch (\Throwable $e) {    // keep the default}

The natural vs technical CQL syntax thread is handy if you want to see the two ways to write the same condition.

Was this helpful?
PRPriya Raghavan

worth adding one behavior that trips people up: undefined variables evaluate to false by design. so if you reference something that is not set for that visitor, the condition just comes back false rather than erroring. good for safety, but it means a typo in an attribute name fails quietly instead of shouting, so double check names.

also fwiw queries are 1 to 500 characters and target sub-20ms evaluation, so keeping conditions tight is both faster and easier to read. if you are calling evaluate on every pageview the per-pageview evaluate budget thread is worth a look.

Was this helpful?
Rrui.tavares

worked. swapped the per-case slot fetches for a couple of evaluate calls with fallbacks and the branching is way cleaner now. the undefined-to-false note saved me, had a mistyped attribute

Still have questions?