Symfony – Expression


Symfony – Expression


”;


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 SymfonyComponentExpressionLanguageExpressionLanguage; 
$language = new ExpressionLanguage();

Step 3 − Test a simple expression.

echo "Evaluated Value: " . $language->evaluate(''10 + 12'') . "rn" ; 
echo "Compiled Code: " . $language->compile(''130 % 34'') . "rn" ;

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,)) . "rn";  
echo "Is Product price higher than 5: " . $language 
   ->evaluate(''product.price > 5'', array(''product'' => $product,)) . "rn"; 

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.

main.php

<?php 
   require __DIR__ . ''/vendor/autoload.php''; 
   use SymfonyComponentExpressionLanguageExpressionLanguage; 
   $language = new ExpressionLanguage();  

   echo "Evaluated Value: " . $language->evaluate(''10 + 12'') . "rn" ; 
   echo "Compiled Code: " . $language->compile(''130 % 34'') . "rn" ;  
   
   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,)) . "rn"; 
   echo "Is Product price higher than 5: " . $language 
      ->evaluate(''product.price > 5'', array(''product'' => $product,)) . "rn"; 
?> 

Result

Evaluated Value: 22 
Compiled Code: (130 % 34) 
Product price is 10 
Is Product price higher than 5: 1

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *