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
ExpressionFunctioninstances 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
Après avoir monté une nouvelle équipe de développement, nous avons procédé à la migration de toute l’infrastructure technique sur une nouvelle architecture fortement dynamique à base de Symfony2, RabbitMQ, Elasticsearch et Chef. Les gains en performance, en stabilité et en capacité de développement permettent à l’entreprise d’engager de nouveaux marchés…
Au fil de notre collaboration avec Deezer, nous avons été impliqués dans plusieurs initiatives visant à optimiser les performances de leur plateforme. Notre engagement initial s’est concentré sur le soutien et le conseil à l’équipe “Product Features” lors de leur projet de migration en cours. Nous avons apporté notre expertise pour résoudre…
JoliCode accompagne l’équipe technique Dayuse dans l’optimisation des performances de sa plateforme. Nous sommes intervenus sur différents sujets : La fonctionnalité de recherche d’hôtels, en remplaçant MongoDB et Algolia par Redis et Elasticsearch. La mise en place d’un workflow de réservation, la migration d’un site en Twig vers une SPA à base de…