2

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?

Tim Otten
  • 171
  • 1
  • 5
  • Note that an expression language can also be safer than JS/PHP `eval()` because it doesn't allow arbitrary code execution.... and it's not even Turing-complete. – Tim Otten Dec 08 '15 at 03:24
  • [Handlebars](http://handlebarsjs.com/) is a superset of mustache, would that work for you? I use that across PHP/Javascript projects and am pretty happy with it. – Sean DuBois Dec 10 '15 at 00:51
  • Ooh, that's a neat idea. Unfortunately, some quick searching suggests that it doesn't natively support common conditional notations: http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional – Tim Otten Dec 10 '15 at 06:05
  • There may not be an answer... started thinking about how to do it myself... https://gist.github.com/totten/ce37971dfdd029c40b08 ... – Tim Otten Dec 10 '15 at 23:07

1 Answers1

2

Was faced with a similar issue of handling expressions on my client-side, but also being able to understand those same expressions on the server-side.

Stumbled upon a JS port of the Symfony Expression Language for PHP. Seems to be very robust and have not had any issues so far.

hackerESQ
  • 99
  • 8