Norway



Nicolas Grekas  - 6baa34bc1e5c347b1003f6abe8691de1 s 100 - Inlined routing configuration (Symfony Blog)

The Routing component allows to define requirements and
default values for route placeholders using the requirements and
defaults options respectively.

For example, in the following route defined with PHP annotations, the page
placeholder is restricted to only accept integers and its default value is 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

use SymfonyComponentRoutingAnnotationRoute;

class BlogController extends Controller
{
    /**
     * @Route("//{page}", name="_list", requirements={"page"="d+"}, defaults={"page"="1"})
     */
    public function list($page)
    {
        // ...
    }
}

This route config is a bit verbose for simple conditions. That’s why in Symfony
4.1 you can inline the route requirements and default values in the placeholders.
The previous example in Symfony 4.1 can look like this:

/**
 * @Route("/blog/{page<d+>?1}", name="blog_list")
 */
public function list($page)
{
    // ...
}

The new syntax is {placeholder-name<requirements>?defaults}, every part of
it is optional and it works in all config formats (annotations, YAML and XML):

blog_list:
    # no requirements and no default value
    path: /blog/{page}
    # with requirements but no default value
    path: /blog/{page<d+>}
    # no requirements but with a default value
    path: /blog/{page?1}
    # no requirements but with default value = null
    path: /blog/{page?}
    # with requirements and default value = null
    path: /blog/{page<.*>?}

You can inline the config for multiple placeholders in the same route, but if
there are lots of placeholders or the conditions are complex, the resulting
config may be less readable and you should probably revert to the previous syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// this config may be too complex to inline it:

/** @Route("/{_locale<en|es|fr>?en}/blog/{category<|releases|>?}/{page<d+>?1}", name="blog_list") */
public function list($page) { }

// in this case it may be better to keep using the traditional syntax

/**
 * @Route("/{_locale}/blog/{category}/{page}", name="blog_list",
 *   "requirements"={"_locale": "en|es|fr", "category": "news|releases|security", "page": "d"},
 *   "defaults"={"_locale": "en", "category": "news", "page": "1"}
 * )
 */
public function list($page) { }



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here