How to define routes in Symfony?

In Symfony, routes are defined in a file called routes.yaml or annotations in the config directory of your Symfony project.

To define routes in Symfony, you can use the following syntax:

  1. Using YAML format:
# config/routes.yaml app_home: path: / controller: App\Controller\HomeController::index

In this example, we define a route named app_home that corresponds to the root URL / and is handled by the index method in the HomeController class.

  1. Using annotations:
// src/Controller/HomeController.php use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Response; class HomeController extends AbstractController { /** * @Route("/", name="app_home") */ public function index(): Response { return $this->render('home/index.html.twig'); } }

In this example, we use annotations to define the route directly within the controller class. The @Route annotation specifies the path for the route along with the route name.

After defining routes, you need to import the routes.yaml or annotations file in your config/routes.yaml file to make them available in your Symfony application.

# config/routes.yaml imports: - { resource: routes.yaml }

These are the two common ways to define routes in Symfony using YAML or annotations. With routes defined, you can map URLs to controller actions and handle requests in your Symfony application.