As we discussed earlier, expression language is one of the salient features of Symfony application. Symfony expression is mainly created to be used in a configuration environment. It enables a non-programmer to configure the web application with little effort. Let us create a simple application to test an expression.
Step 1 − Create a project, expression-language-example.
cd /path/to/dir mkdir expression-language-example cd expression-language-example composer require symfony/expression-language
Step 2 − Create an expression object.
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; $language = new ExpressionLanguage();
Step 3 − Test a simple expression.
echo "Evaluated Value: " . $language->evaluate('10 + 12') . "\r\n" ; echo "Compiled Code: " . $language->compile('130 % 34') . "\r\n" ;
Step 4 − Symfony expression is powerful such that it can intercept a PHP object and its property as well in the expression language.
class Product { public $name; public $price; } $product = new Product(); $product->name = 'Cake'; $product->price = 10; echo "Product price is " . $language ->evaluate('product.price', array('product' => $product,)) . "\r\n"; echo "Is Product price higher than 5: " . $language ->evaluate('product.price > 5', array('product' => $product,)) . "\r\n";
Here, the expression product.price and product.price > 5 intercept $product object's property price and evaluate the result.
The complete coding is as follows.
<?php require __DIR__ . '/vendor/autoload.php'; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; $language = new ExpressionLanguage(); echo "Evaluated Value: " . $language->evaluate('10 + 12') . "\r\n" ; echo "Compiled Code: " . $language->compile('130 % 34') . "\r\n" ; class Product { public $name; public $price; } $product = new Product(); $product->name = 'Cake'; $product->price = 10; echo "Product price is " . $language ->evaluate('product.price', array('product' => $product,)) . "\r\n"; echo "Is Product price higher than 5: " . $language ->evaluate('product.price > 5', array('product' => $product,)) . "\r\n"; ?>
Evaluated Value: 22 Compiled Code: (130 % 34) Product price is 10 Is Product price higher than 5: 1