How to Register custom DQL Functions

Edit this page

How to Register custom DQL Functions

Doctrine allows you to specify custom DQL functions. For more information on this topic, read Doctrine's cookbook article DQL User Defined Functions.

In Symfony, you can register your custom DQL functions as follows:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
# config/packages/doctrine.yaml
doctrine:
    orm:
        # ...
        dql:
            string_functions:
                test_string: App\DQL\StringFunction
                second_string: App\DQL\SecondStringFunction
            numeric_functions:
                test_numeric: App\DQL\NumericFunction
            datetime_functions:
                test_datetime: App\DQL\DatetimeFunction

Note

In case the entity_managers were named explicitly, configuring the functions with the ORM directly will trigger the exception Unrecognized option "dql" under "doctrine.orm". The dql configuration block must be defined under the named entity manager.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
# config/packages/doctrine.yaml
doctrine:
    orm:
        # ...
        entity_managers:
            example_manager:
                # Place your functions here
                dql:
                    datetime_functions:
                        test_datetime: App\DQL\DatetimeFunction

Caution

DQL functions are instantiated by Doctrine outside of the Symfony service container so you can't inject services or parameters into a custom DQL function.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
Symfony 6.2 is backed by Sulu.
Symfony 6.2 is backed by Les-Tilleuls.coop.