简体   繁体   中英

Symfony 2 @Route annotation case-sensitive

I'm trying to create a url with annotations of the route.

The problem is that I can write any URL large, small or different.

@Route("/{staat}/", name="showStaats",requirements={"location" = "berlin|bayern|brandenburg"})

This URL can be accessed both from www.example.com/berlin and under www.example.com/Berlin .

I would, however, that it is attainable only under www.example.com/berlin .

Answering the question "How to make case-insensitive routing requirement":

You can add case-insensitive modifier to requirement regexp like so:

(?i:berlin|bayern|brandenburg)

You have "/{staat}/" , but your requirements set "location" = ... , these should match, so maybe that's the cause of your problem.

If you don't want to hardcode the list of states in your route, you could inject a service containter parameter with a list of states. Just see How to use Service Container Parameters in your Routes in the documentation for how to do that.

If you just want to check, whether that state is all lower-cased you could try the following requirement:

staat: "[a-z-]+"

This should match only lowercase characters and dash (eg for "sachsen-anhalt"). But I'm not entirely sure if this will work as the router's regex-detection is a bit quirky.

You could also create a custom Router Loader which will create routes programmatically, eg by fetching the list of states from a database or file.

edit :

As I wrote in my comment I would add the list of params as a Service Container parameter, eg %my_demo.states% containing a list of states. I'm not sure however if this will work with annotations. So here is a quick workaround how to get it working.

In your app/config/config.yml you append the %my_demo.states% parameter:

my_demo:
    states: ["berlin", "brandenburg", "sachsen-anhalt", ... ]

In your app/config/routing.yml there should be something like this:

my_demobundle:
    resource: "@MyDemoBundle/Controller/"
    prefix:   /
    type:     annotation

The type: annotation and @MyDemoBundle is the relevant part. Add the following route before this one, to make sure it takes precedence:

showStaats:
    path:     /{state}
    defaults: { _controller: MyDemoBundle:State:index }
    requirements:
        state: %my_demo.states%

This will add a route which will apply before your annotations using the list of states as parameters. This is a bit crude, as you are mixing yml/annotation-based routing, but it's imo still better than cramming a list of 16 states in the annotation, not to mention its easier to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM