Silverstripe URL模式$ url_handlers无法正常工作 - 名称空间似乎与

时间:2017-03-28 04:22:00

标签: php routing silverstripe

当我尝试使用以下$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/1update操作匹配。

我添加了哪些额外的细节才能使这些模式有效?

1 个答案:

答案 0 :(得分:4)

我在Silverstripe Users Slack

zippy flamerohr 的帮助下找到了答案

网址格式应按照最具体的最不具体的的顺序定义。

选项1:

正确地重新排序模式,并在变量之间添加一个静态段,以便添加的特性可以避免模式在匹配时不应该例如

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',
);

选项2:

正确地重新排序模式,并使用!约定来定义必须提供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