标题说明了一切:是否可以为在uri_paths
of RestResource中配置的参数设置耳聋值?我看了一下RestResource
的代码,我觉得它不受支持,因为uri_paths
只是一张地图;但是,我仍然认为值得问这个问题:)
发布于 2022-08-19 10:59:44
是的,ResourceBase
在ResourceBase::routes()
中生成一个RoutingCollection
,然后您可以循环使用它(参见https://api.drupal.org/api/drupal/core%21modules%21rest%21src%21Plugin%21ResourceInterface.php/function/ResourceInterface%3A%3Aroutes/8.2.x)。
假设您的uri_paths
如下所示:
uri_paths = {
"canonical" = "/api/fetch/{some_id}"
}
只需在您自己的资源中重写该方法,从父服务器(例如,RoutingCollection
)获取ResourceBase
,并为您的参数设置一个默认参数。
就像这样:
public function routes(): RouteCollection {
$collection = parent::routes();
// Add a default of NULL for the 'some_id' optional parameter.
foreach ($collection->all() as $route) {
$route->addDefaults(['some_id' => NULL]);
}
return $collection;
}
然后,当调用中没有提供该参数时,该参数应该得到该默认值。
因此,如果您的get()
是这样的:
public function get($some_id = NULL): ResourceResponse { .. }
对/api/fetch/2
的GET调用将$some_id
设置为2,而对/api/fetch
的GET调用将$some_id
设置为NULL
。
https://drupal.stackexchange.com/questions/310872
复制相似问题