I work with a web application that uses heavy mix of server-side PHP and client-side Javascript, and I would like to allow administrators to configure some basic conditionals. For example, we might have a data model with:
var person = {
name: 'Alice',
age: 33,
favorite_color: 'purple',
address: {street: '123 Some St', state: 'NY'}
};
An administrator might want to hide a field or trigger an action based on a conditional like:
((person.age > 20) or (person.favorite_color == 'red')) and (person.address.state == 'NY')
Ideally, we could use the same conditionals in different contexts -- such as client-side validation and server-side validation.
If the application were only server-side PHP, or if it were full-stack JS, then you could use PHP eval()
or JS eval()
. But for an application that involves multiple languages, this doesn't work. It seems like one would need to create a small DSL with implementations for different platforms, eg
// JS
var condition = "(person.age > 20) or (person.favorite_color == 'red')";
var isMatch = ExpressionLanguage.eval(condition, {
person: {...}
})
// PHP
$condition = "(person.age > 20) or (person.favorite_color == 'red')";
$isMatch = ExpressionLanguage::eval($condition, array(
'person' => array(...),
));
I've encountered mustache, which takes a similarly portable approach to templating. However, its design is specifically "logic-less" and does not support conditions. Never-the-less, it seems like a common enough problem. How have others addressed the desire for portable conditionals?