Use Service for Route Condition in Symfony 7

Use Service for Route Condition in Symfony 7

Symfony provides the condition option that can be used to evaluate complex conditions to determine whether some incoming URL should match a specific controller. Conditions can be based on various factors such as request attributes, HTTP methods, or even custom logic. Service can also be used for defining route condition. By leveraging services for route conditions, developers can encapsulate complex logic into reusable and testable components, promoting a modular and maintainable codebase. This tutorial explains how to use service for route condition in Symfony 7.

In the route condition, utilize the service function by passing the name of the service you intend to invoke.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/', condition: "service('App\\\\Service\\\\RouteChecker').check(request)")]
    public function index(): Response
    {
        return new Response('Hello');
    }
}

config/routes.yaml

test_index:
    path: /
    controller: App\Controller\TestController::index
    condition: "service('App\\\\Service\\\\RouteChecker').check(request)"

By default, and for optimization purposes, we cannot call any of the services defined in the application. To make services available in route conditions, we must mark them with the #[AsRoutingConditionService] attribute.

src/Service/RouteChecker.php

<?php

namespace App\Service;

use Symfony\Bundle\FrameworkBundle\Routing\Attribute\AsRoutingConditionService;
use Symfony\Component\HttpFoundation\Request;

#[AsRoutingConditionService]
class RouteChecker
{
    public function check(Request $request): bool
    {
        return 1 === $request->query->getInt('test');
    }
}

Instead of using the complete service name within the expression, the alias option can be utilized to designate the service alias. In the preceding example, it can be presented as follows:

#[AsRoutingConditionService(alias: 'route_checker')]

Within the route condition, it appears as follows:

#[Route('/', condition: "service('route_checker').check(request)")]

Leave a Comment

Cancel reply

Your email address will not be published.