Interpreter Pattern
debt(d7/e5/b5/t3)
Closest to 'only careful code review or runtime testing' (d7). The detection_hints indicate automated detection is 'no' and the tool listed (phpstan) would not flag misapplication of this design pattern — it cannot detect that you've used a giant switch/nested if-else where an interpreter pattern would be appropriate, nor that you've applied interpreter to an overly complex grammar. Only code review or runtime performance testing would reveal misuse.
Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix describes defining a grammar as multiple PHP classes (BooleanExpression, AndExpression, OrExpression), which means either introducing or replacing an existing ad-hoc implementation requires creating several new classes and reworking the evaluation logic across a component. Common mistakes like switching to a proper parser generator for complex grammars would also be a multi-file change.
Closest to 'persistent productivity tax' (b5). The pattern applies to web and cli contexts and affects the core rule/expression evaluation subsystem. Once adopted, every new grammar rule or business condition requires a new class, and all maintainers must understand the pattern's structure. It's not architectural (b7-b9) but it does impose a persistent tax on the component and teams touching DSL logic.
Closest to 'minor surprise (one edge case)' (t3). The misconception field states devs think 'Interpreter is for building general-purpose languages' when it's actually most useful for small DSLs with well-defined grammars. This is a scoping misconception rather than a behavioral gotcha — a competent developer will likely discover the correct usage relatively quickly, making it a minor rather than serious trap.
Also Known As
TL;DR
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
Why It Matters
Common Mistakes
- Using for complex grammars — use proper parser
- Not caching parsed expressions
- No error handling in terminals
Code Examples
function evalRule(string $rule, Order $o): bool {
if (preg_match('/total > (\d+)/',$rule,$m)) return $o->total > $m[1];
// Cannot handle AND, OR
}
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); }
}