symfony3 Routing Routing using annotations


Example

The routing configuration is included in your app/config/config.yml file, by default the app/config/routing.yml file.

From there you can link to the controllers that have annotated routing configuration:

# app/config/routing.yml

app:
    resource: "@AppBundle/Controller"
    type:     annotation

In your own bundle you can configure, routes which serve two purposes:

  • Matching against a request, such that the correct action is called for the request.
  • Generating an URL from the name and route parameters.

Below is an example annotated route configuration:

// src/AppBundle/Controller/DefaultController.php

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 * @Route("/application")
 */
class DefaultController extends Controller {
    /**
     * @Route("/content/page/{parameter}",
     *        name="my_page",
     *        requirements={"parameter" = "\d+"},
     *        defaults={"parameter" = 42})
     * @Method({"GET", "PUT"})
     */
    public function myPageAction($parameter)
    {
        // ...
    }
}

The controller is annotated with a prefix route, such that any configured route in this controller will be prepended using the prefix.

The configured route is named my_page, and calls the myPageAction function when requested. It has a parameter, named parameter with a default value. The value is only valid when it matches the regex \d+. For this route, only the HTTP methods GET and PUT are accepted.

Notice that the parameter is injected into the action as a function parameter.

A generated route with the parameter value of 10 might look like /application/content/page/10.