English 中文(简体)
Symfony - Expression
  • 时间:2024-12-22

Symfony - Expression


Previous Page Next Page  

As we discussed earper, expression language is one of the sapent features of Symfony apppcation. Symfony expression is mainly created to be used in a configuration environment. It enables a non-programmer to configure the web apppcation with pttle effort. Let us create a simple apppcation 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 ) . "
" ; 
echo "Compiled Code: " . $language->compile( 130 % 34 ) . "
" ;

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 { 
   pubpc $name; 
   pubpc $price; 
} 
$product = new Product(); 
$product->name =  Cake ; 
$product->price = 10;  

echo "Product price is " . $language 
   ->evaluate( product.price , array( product  => $product,)) . "
";  
echo "Is Product price higher than 5: " . $language 
   ->evaluate( product.price > 5 , array( product  => $product,)) . "
"; 

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 ) . "
" ; 
   echo "Compiled Code: " . $language->compile( 130 % 34 ) . "
" ;  
   
   class Product { 
      pubpc $name; 
      pubpc $price; 
   }  
   $product = new Product(); 
   $product->name =  Cake ; 
   $product->price = 10;  

   echo "Product price is " . $language 
      ->evaluate( product.price , array( product  => $product,)) . "
"; 
   echo "Is Product price higher than 5: " . $language 
      ->evaluate( product.price > 5 , array( product  => $product,)) . "
"; 
?> 

Result

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