Silverstripe $ url_handlers url patterns not working - namespaces seem to be in conflict
When I try to create routes for a RESTful API with the following $url_handlers
, it creates a conflict between the two patterns.
class API extends Controller {
...
private static $url_handlers = array(
'GET object' => 'read',
'POST object' => 'create',
'PUT object/$ID' => 'update',
'PUT object/$ID/$OtherID' => 'assign',
'DELETE object/$ID' => 'delete',
'DELETE object/$ID/$OtherID' => 'unassign',
);
...
}
object/1
works great but object/1/1
fits the action update
.
What additional details can I add to make these templates work?
source to share
I found the answer with zippy and flamerohr on Silverstripe Users Slack
URL patterns should be specified in order of most specific to least specific.
Option 1:
Edit the templates correctly and add a static segment between the variables so that the added specifics avoid template matching when it shouldn't, for example
private static $url_handlers = array(
'GET object' => 'read',
'POST object' => 'create',
'PUT object/$ID/static-segment/$OtherID' => 'assign',
'PUT object/$ID' => 'update',
'DELETE object/$ID/static-segment/$OtherID' => 'unassign',
'DELETE object/$ID' => 'delete',
);
Option 2:
Edit the templates correctly and use a convention !
to determine that the URL parameter must be provided to match the template, for example
private static $url_handlers = array(
'GET object' => 'read',
'POST object' => 'create',
'PUT object/$ID/$OtherID!' => 'assign',
'PUT object/$ID' => 'update',
'DELETE object/$ID/$OtherID!' => 'unassign',
'DELETE object/$ID' => 'delete',
);
This convention can be found in the Silverstripe documentation Routing
:
https://docs.silverstripe.org/en/3.2/developer_guides/controllers/routing/#url-patterns
source to share