Master Symfony ExpressionLanguage: Install, Use, and Extend with Custom Functions
This guide explains how to install Symfony's ExpressionLanguage component, use it for evaluating and compiling expressions, parse and lint code, register custom functions, and work with objects, providing practical PHP examples and integration tips for backend development.
Installation
Install the component via Composer: composer require symfony/expression-language If the component is used outside a Symfony application, include vendor/autoload.php to enable Composer's autoloader.
Why Use ExpressionLanguage?
The component lets you write expressions in configuration files to implement complex logic such as security rules, validation constraints, and route matching. It also serves as a lightweight business‑rule engine, allowing non‑PHP administrators to configure behavior safely.
Basic Usage
ExpressionLanguage can evaluate an expression directly or compile it into PHP code for caching.
<?php
require '../vendor/autoload.php';
$el = new \Symfony\Component\ExpressionLanguage\ExpressionLanguage();
var_dump($el->evaluate('1 + 2')); // displays 3
var_dump($el->compile('1 + 2')); // displays (1 + 2)
?>Parsing and Linting
The parse() method returns a ParsedExpression object that represents the internal structure of an expression. Symfony does not provide a dedicated lint() method; instead you can attempt to parse the expression and catch a SyntaxError to detect invalid syntax.
<?php
require '../vendor/autoload.php';
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
$el = new ExpressionLanguage();
try {
$el->lint('1 + 2 * (3 - 4');
echo "Expression syntax is correct
";
} catch (\Symfony\Component\ExpressionLanguage\SyntaxError $e) {
echo "Syntax error: " . $e->getMessage() . "
";
}
?>Registering Custom Functions
Functions are registered per ExpressionLanguage instance using register(), which accepts a name, a compiler callback, and an evaluator callback.
<?php
require '../vendor/autoload.php';
$el = new \Symfony\Component\ExpressionLanguage\ExpressionLanguage();
$el->register('custom_function',
function ($str) { return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str); },
function ($args, $str) { return is_string($str) ? strtolower($str) : $str; }
);
var_dump($el->evaluate('custom_function("HELLO")'));
?>The evaluator receives an arguments array as its first parameter, containing the values passed to evaluate().
Objects and Their Properties
Expressions can access PHP objects and their properties directly.
<?php
require '../vendor/autoload.php';
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
$el = new ExpressionLanguage();
class Product { public $name; public $price; }
$p = new Product();
$p->name = 'Tinywan';
$p->price = 2024;
echo $el->evaluate('product.price', ['product' => $p]) . "
";
echo $el->evaluate('product.price > 2022', ['product' => $p]) . "
";
?> Product price is 2024
Is Product price higher than 2022: 1Other Applications
The component can be integrated with access‑control libraries such as PHP‑Casbin. Example code shows how to create an ExpressionLanguage instance, register functions, parse a policy expression, and evaluate it to obtain an allow/deny decision.
protected function getExpressionLanguage(array $functions): ExpressionLanguage {
$el = new ExpressionLanguage();
foreach ($functions as $key => $func) {
$el->register($key,
function (...$args) use ($key) { return sprintf($key.'(%s)', implode(',', $args)); },
function ($arguments, ...$args) use ($func) { return $func(...$args); }
);
}
return $el;
}
$el = $this->getExpressionLanguage($functions);
$expression = $el->parse($expWithRule, array_merge($rTokens, $pTokens));
$result = $el->evaluate($expression, $parameters);
if ($result) { $policyEffects[0] = Effector::ALLOW; } else { $policyEffects[0] = Effector::INDETERMINATE; }Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
