📅  最后修改于: 2020-10-19 03:14:13             🧑  作者: Mango
如前所述,表达语言是Symfony应用程序的显着特征之一。 Symfony表达式主要是为了在配置环境中使用而创建的。它使非程序员可以轻松配置Web应用程序。让我们创建一个简单的应用程序来测试表达式。
步骤1-创建一个项目expression-language-example 。
cd /path/to/dir
mkdir expression-language-example
cd expression-language-example
composer require symfony/expression-language
步骤2-创建一个表达式对象。
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
$language = new ExpressionLanguage();
步骤3-测试一个简单的表达式。
echo "Evaluated Value: " . $language->evaluate('10 + 12') . "\r\n" ;
echo "Compiled Code: " . $language->compile('130 % 34') . "\r\n" ;
步骤4 -Symfony表达式功能强大,可以在表达式语言中拦截PHP对象及其属性。
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";
在这里,表达式product.price和product.price> 5拦截$ product对象的属性价格并评估结果。
完整的编码如下。
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