Adding PHP Function to Symfony ExpressionLanguage, The Simple Way 👌
Today I want to share a quick tip for Symfony users ✌️. When you use the ExpressionLanguage component you get a context: some variables and some functions.
Those functions are not the same everywhere. For example when using the validation constraint Expression
:
#[Assert\Expression(
"is_valid(this.getCategory()) or is_valid(this.getSection())",
message: 'Bad category!',
)]
class BlogPost
{
// ...
}
You get a custom ExpressionLanguage service, defined like this:
// The language itself with a custom provider
->set('validator.expression_language', ExpressionLanguage::class)
->args([service('cache.validator_expression_language')->nullOnInvalid()])
->call('registerProvider', [
service('validator.expression_language_provider')->ignoreOnInvalid(),
])
// The custom provider
->set('validator.expression_language_provider', ExpressionLanguageProvider::class)
This service has a provider attached, it’s the proper way to extend the functionality in ExpressionLanguage. It implements the interface ExpressionFunctionProviderInterface
and looks like this:
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions(): array
{
return [
new ExpressionFunction('is_valid', function (...$arguments) {
return true; // Redacted for clarity
}, function (array $variables, ...$arguments): bool {
return true; // Redacted for clarity
}),
];
}
}
It’s great to add custom functions (is_valid
here), but what if I just need to add count()
support?!
The recommended way is to use this interface like that, with the fromPhp
shortcut:
class CustomExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions(): array
{
return [
ExpressionFunction::fromPhp('count');
];
}
}
🤔 But wait, can’t this be done without PHP code?!
Section intitulée the-del-lazy-del-simple-wayThe lazy simple way
As ExpressionFunction::fromPhp
is a static callable, we can call it like a Factory to build the ExpressionFunction
we need.
So by leveraging the power of Symfony DIC, we can:
- override the framework ExpressionLanguage used in the Validator component;
- add
ExpressionFunction
instances on the fly.
All of that with zero line of PHP 😎 🎉
countableExpression:
class: Symfony\Component\ExpressionLanguage\ExpressionFunction
factory: ['Symfony\Component\ExpressionLanguage\ExpressionFunction', 'fromPhp']
arguments: ['count']
validator.expression_language:
class: Symfony\Component\ExpressionLanguage\ExpressionLanguage
calls:
- [addFunction, ['@countableExpression']]
- [registerProvider, ['@validator.expression_language_provider']]
We can add as many functions as needed here without relying on the ExpressionFunctionProviderInterface
.
⚠️ Doing so, we are now duplicating in our code the validator.expression_language
original definition, this could lead to issues if the framework definition is updated. The original version of this article was using decorates
but it does not keep the original service the way we need.
Section intitulée use-the-forceUse the force
There were four ways to add this count
function in ExpressionLanguage:
- install a bundle;
- create a Provider and set it up in the configuration;
- drop ExpressionLanguage and use plain PHP instead (Callback constraint);
- use the DIC configuration to my advantage.
For my case, I consider the last one the most efficient and simple. What about you? Would you have chosen another?
The DIC configuration is really powerful and if options like factory
and decorates
are new to you, I strongly recommend taking some time to read about it 🤓 you will thank me later.
Cheers 👋
Commentaires et discussions
Nos formations sur ce sujet
Notre expertise est aussi disponible sous forme de formations professionnelles !

Symfony avancée
Découvrez les fonctionnalités et concepts avancés de Symfony
Ces clients ont profité de notre expertise
Ouibus a pour ambition de devenir la référence du transport en bus longue distance. Dans cette optique, les enjeux à venir de la compagnie sont nombreux (vente multi-produit, agrandissement du réseau, diminution du time-to-market, amélioration de l’expérience et de la satisfaction client) et ont des conséquences sur la structuration de la nouvelle…
Nous avons entrepris une refonte complète du site, initialement développé sur Drupal, dans le but de le consolider et de jeter les bases d’un avenir solide en adoptant Symfony. La plateforme est hautement sophistiquée et propose une pléthore de fonctionnalités, telles que la gestion des abonnements avec Stripe et Paypal, une API pour l’application…
Travailler sur un projet US présente plusieurs défis. En premier lieu : Le décalage horaire. Afin d’atténuer cet obstacle, nous avons planifié les réunions en début d’après-midi en France, ce qui permet de trouver un compromis acceptable pour les deux parties. Cette approche assure une participation optimale des deux côtés et facilite la communication…