5

Does Drupal's routing system support a regular expression or other means for multiple route paths? I have a route that I would like to be able to hit from two different endpoints, /api/v1/foo and /api/v1/foo_bar. One route is newer, the other I want to keep for backwards compatibility reasons.

In my module's my_module.routing.yml file, I have defined:

foo:
  path: 'api/v1/foo'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

foo_bar:
  path: 'api/v1/foo_bar'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

This works, but as you can see everything after the route name and path property is copy/pasted. It's not exactly adhering to the DRY principle. Now this is a simple case, but imagine if I had a much more involved route with complex requirements and parameters. There would be a very high chance of making a typo or pasting mistake in one.

Is it possible to define the path as a regular expression or something similar so I don't have to repeat all the route properties?

1
3
cool:
  path: 'api/v1/{dynamic}'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

Then in your controller

public function doItAction($dynamic) {

  if($dynamic == 'foo' || $dynamic == 'foo_bar') {
    // your code
  } 

}
1
  • 2
    Thanks for the reply. The problem with this is that I have many paths of the form api/v1/{dynamic} (besides the ones above, that map to different controllers), meaning they would all get captured by this one route rule. That would bloat the Controller action with a bunch of checking logic and sort of defeat the purpose of having a routing file. – The Unknown Dev Mar 12 '18 at 23:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.