Symfony News

New in Symfony 5.1: Routing improvements

Symfony 5.1 adds important new features related to routing, such as priority for route annotations and simpler route config. In this article we'll show other minor but interesting features added to routing.

Added stateless route attribute

Contributed by
Mathias Arlaud
in #35732 and #35782.

Routes can now configure a stateless boolean option. If set to true, they declare that session won't be used during the handling of the request.

If a stateless route uses the session, you'll see an exception when debug is enabled in the application and you'll get a log message when debug is disabled:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// src/Controller/MainController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class MainController extends AbstractController
{
    /**
     * @Route("/", name="homepage", stateless=true)
     */
    public function homepage()
    {
        // ...
    }
}

Allow using env vars in route conditions

Contributed by
Ahmed Tailouloute
in #35747.

Routing conditions define expressions that routes must match. In Symfony 5.1, we've improved those expressions to allow using environment variables.

When using env vars, you can also apply any of the Symfony env var processors:

1
2
3
4
5
6
7
8
/**
 * @Route("/new-feature", condition="env('bool:IS_FEATURE_ENABLED') === true")
 */
public function __invoke()
{
    // this route will only execute when the value of the
    // IS_FEATURE_ENABLED env var is TRUE
}

Simpler RequestContext configuration

Contributed by
Benjamin Lévêque
in #35281.

Generating URLs in console commands and any other place outside of the web context is challenging because Symfony doesn't have access to the current host, the base URL, etc.

In those cases, you need to configure the request context using container parameters such as router.request_context.host. In Symfony 5.1, you can configure those values via the framework.router option:

1
2
3
4
5
6
7
# config/packages/routing.yaml
framework:
    router:
        # ...
        host: 'example.org'
        scheme: 'https'
        base_url: 'my/path'

Be trained by Symfony experts - 2020-04-6 Online Europe - 2020-04-6 Online Europe - 2020-04-8 Online Europe


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook