Symfony - 表达


正如我们之前讨论的,表达式语言是 Symfony 应用程序的显着特征之一。Symfony 表达式主要是为了在配置环境中使用而创建的。它使非程序员能够轻松配置 Web 应用程序。让我们创建一个简单的应用程序来测试表达式。

步骤 1 - 创建一个项目,表达式语言示例

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.priceproduct.price > 5截取$product对象的属性price并评估结果。

完整的编码如下。

main.php

<?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