Real World Example Use Of The Symfony Expression Language
Recently I’ve had the pleasure of getting my hands dirty with the Symfony Expression Language. The opportunity arose because I was saddled with a really cool task of developing a custom calculator tailored for the financial advising industry. At my job, my teammates and I mainly work with the Symfony framework for the majority of our projects.
Without diving into this large project’s details and all the code it took to make it, (which would simply take way too long to explain), I want to stick with the topic of how easy it was to use the expression language itself. However, I feel a brief overview of the steps that lead to creating a string that I gets passed to the Expression Language class is probably necessary.
Let’s first look at the UI of the calculator I created. There is a lot going on here. Basically, the user can select from the menu on the left an operator, number, function, or variable that builds the html on the right (tabbed area). Each row and item in the html calculation itself can be deleted, sorted, or duplicated and certain items like functions can have infinitely nested items. Cool, right!?
I then wrote a few jQuery scripts that parse through the calculator’s html, first building a multidimensional array that is then used to build a JSON object out of it that gets passed to a service class through a controller action.
In a nutshell the service loops through the JSON object and creates a string for the expression language to evaluate. I made it so that the expression language itself didn’t have to evaluate variables, objects, hashes, booleans, arrays, or methods because I wanted to handle those on my end for accuracy and reliability. However, you can do that with the Expression Language component as well.
I am simply passing operators and numbers concatenated together in a string. The awesome thing about the component is how reliably it takes care of operator precedence, which is one of two reasons I used it, the other was to avoid the dangerous eval()
function.
Let’s take a look at the service that utilizes the Expression Language, more specifically, the method. The $this->looper
is a private method that, you guessed it, loops through the array and builds the string to pass to the Expression Language. It’s really a breeze from here, declare a new ExpressionLanguage()
instance and then I call the evaluate method passing the string. Easy peasy!
looper($calcArray); // Pass the expression string to the expression object $language = new ExpressionLanguage(); return $language->evaluate($calcString); } catch( \Exception $e) { return $e->getMessage(); } }
Just for curiosities sake, let’s look at an example string that would get passed to the evaluate method. My looper method could create a string that looks like this: 65*10+0.04-65/85*9.54
and the Expression Engine gives us an answer of 642.74470588235
. Pretty cool if you ask me!
No Comments