当我尝试使用以下$url_handlers
为RESTful API创建路由时,似乎在两个模式之间产生冲突。
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
工作正常,但object/1/1
与update
操作匹配。
我添加了哪些额外的细节才能使这些模式有效?
答案 0 :(得分:4)
网址格式应按照最具体的到最不具体的的顺序定义。
正确地重新排序模式,并在变量之间添加一个静态段,以便添加的特性可以避免模式在匹配时不应该例如
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',
);
正确地重新排序模式,并使用!
约定来定义必须提供URL参数以匹配模式,例如
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',
);
此惯例可在Silverstripe的Routing
文档中找到:
https://docs.silverstripe.org/en/3.2/developer_guides/controllers/routing/#url-patterns