Sling Academy
Home/PHP/4 Ways to Create Routes in Symfony

4 Ways to Create Routes in Symfony

Last updated: January 13, 2024

Introduction to Symfony Routing

Routes in Symfony are used to map URLs to controller actions. A route contains a URL pattern, a controller, and action specifics. Symfony offers annotations, YAML, XML, or PHP to define your routes.

This guide covers essential ways to define & manage routes in the Symfony PHP framework. Whether you’re new or seasoned in Symfony, mastering routing is crucial for creating web applications that respond to specific URLs effectively.

4 Approaches to Adding Routes in Symfony

Approach 1: Using Annotations for Routing

Routing via annotations is straightforward. First, install the annotations package using composer require annotations. Then, use the @Route annotation above your controller action to define the path:

/**
 * @Route("/blog/{slug}", name="blog_show")
 */
public function show($slug) {
    // ...
}

Annotations are particularly helpful for keeping the route definition close to the controller logic, making it easier to read.

Approach 2: YAML Configuration Files

Defining routes in a .yaml file (usually routes.yaml) is another common approach:

blog_show:
    path: /blog/{slug}
    controller: App\Controller\BlogController::show

YAML files are clean and separate your routing from your controller code.

Approach 3: XML Configuration Files

XML is more verbose, but can support complex configurations:

<?xml version="1.0" encoding="UTF-8" ?>
<routing>
    <route id="blog_show" path="/blog/{slug}">
        <default key="_controller">App\Controller\BlogController::show</default>
    </route>
</routing>

XML configurations are stored in .xml files inside your application’s config/routes/ directory.

Approach 4: PHP Configurations

Symfony also allows defining routes in PHP files. Here’s how:

use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return function (RoutingConfigurator $routes) {
    $routes->add('blog_show', '/blog/{slug}')->controller([BlogController::class, 'show']);
};

While using PHP files, your routes are defined in code, and you can take advantage of your IDE’s features like refactoring and autocomplete.

Route Parameters

All of the above methods allow you to specify parameters:

/**
 * @Route("/blog/{slug}/{page}",
 *     defaults={"page": 1},
 *     requirements={
 *         "slug": "[a-z0-9-]+",
 *         "page": "\d+"
 *     }
 * )
 */
public function show($slug, $page) {
    // ...
}

The {slug} and {page} are parameters that can be made optional or have defaults as shown above.

Route Prioritization

If two routes match the same URL, the one defined first is matched first. To control the order, you can assign a priority property:

blog_show:
    path: /blog/{slug}
    controller: App\Controller\BlogController::show
    priority: 5

Higher numbers indicate higher priority.

Internationalization

Symfony’s routing system supports internationalization. Define localized routes with _locale:

/**
 * @Route({
 *     "en": "/about-us",
 *     "fr": "/a-propos"
 * }, name="about_us")
 */
public function about() {
    // ...
}

This helps you create multilingual websites effortlessy.

Conclusion

Routing is a fundamental part of web applications. Symfony’s flexible choices for route configuration fits various preferences and complex needs. Understanding these methods allows you to structure your application’s URL patterns and controller bindings coherently, leading to maintainable and scalable code bases.

Next Article: Symfony: Restricting Routes to HTTP Methods

Previous Article: Symfony vs Laravel: Which PHP Framework is Better?

Series: Symfony & Doctrine Tutotirlas

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array