Interpreter Pattern
Also Known As
interpreter
expression evaluator
rule engine
TL;DR
A grammar represented as a class hierarchy — used for search query parsers, expression evaluators, and rule engines.
Explanation
Terminal expressions (values) and non-terminal expressions (AND, OR, NOT) form a composite tree. Parse input to build the tree; interpret evaluates it. PHP use cases: search query parsers, business rule engines. For complex grammars use a proper parser (PHP-Parser) rather than hand-rolling the Interpreter pattern.
Common Misconception
✗ Interpreter is for building general-purpose languages — it is most useful for small DSLs with well-defined grammars.
Why It Matters
The interpreter pattern is most valuable when the grammar is simple and performance is not critical — configuration DSLs, rule engines, and template syntax. Implementing it teaches how parsers and evaluators work at a conceptual level, which transfers directly to understanding how PHP itself executes code. For complex or high-performance needs, it should be replaced by a proper parser generator or embedded scripting language.
Common Mistakes
- Using for complex grammars — use proper parser
- Not caching parsed expressions
- No error handling in terminals
Code Examples
✗ Vulnerable
function evalRule(string $rule, Order $o): bool {
if (preg_match('/total > (\d+)/',$rule,$m)) return $o->total > $m[1];
// Cannot handle AND, OR
}
✓ Fixed
interface Expression { public function interpret(Context $ctx): bool; }
class GreaterThan implements Expression {
public function __construct(private string $f, private float $v) {}
public function interpret(Context $ctx): bool { return $ctx->get($this->f) > $this->v; }
}
class AndExpr implements Expression {
public function __construct(private Expression $l, private Expression $r) {}
public function interpret(Context $ctx): bool { return $this->l->interpret($ctx) && $this->r->interpret($ctx); }
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
23 Mar 2026
Views
26
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 9
Google 6
Perplexity 4
Unknown AI 2
ChatGPT 1
Majestic 1
Ahrefs 1
Also referenced
How they use it
crawler 21
crawler_json 3
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: High
⚡ Quick Fix
Use the interpreter pattern for domain-specific rule languages — define a grammar as PHP classes (BooleanExpression, AndExpression, OrExpression) so business users can write filter rules
📦 Applies To
any
web
cli
🔗 Prerequisites
🔍 Detection Hints
Business rule evaluation via giant switch or nested if/else; user-configurable filter logic evaluated at runtime; domain-specific mini-language needed
Auto-detectable:
✗ No
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: High
Context: File
Tests: Update