我对 api 平台自定义路由功能有疑问。当尝试使用 DELETE 方法实现自定义路由时,事件系统会针对 http 请求中的对象(由参数转换器找到)触发:
* @ApiResource(
* attributes={
* "normalization_context": {
* },
* "denormalization_context": {
* },
* },
* itemOperations={
* },
* collectionOperations={
* "customObjectRemove": {
* "method": "DELETE",
* "path": "/objects/{id}/custom_remove",
* "controller": CustomObjectRemoveController::class,
因此,即使我在控制器中编写了自己的逻辑,我的实体也始终会在 api 平台事件系统中被触发以进行删除。我怎样才能防止这种行为?
您可以实现一个实现 EventSubscriberInterface 的事件订阅者:
<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class DeleteEntityNameSubscriber implements EventSubscriberInterface
{
public function __construct()
{
// Inject the services you need
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onDeleteAction', EventPriorities::PRE_WRITE]
];
}
public function onDeleteAction(GetResponseForControllerResultEvent $event)
{
$object = $event->getControllerResult();
$request = $event->getRequest();
$method = $request->getMethod();
if (!$object instanceof MyEntity || Request::METHOD_DELETE !== $method) {
return;
}
// Do your staff here
}
}
我知道这个问题很老了,但它出现在谷歌结果中。
您可以通过添加
write: false
将路由配置为不删除实体,这会禁用端点的自动删除和刷新功能:
collectionOperations={
* "customObjectRemove": {
* "method": "DELETE",
* "path": "/objects/{id}/custom_remove",
* "controller": CustomObjectRemoveController::class,
* "write": false
注意:您需要在事件订阅者或控制器中添加
flush
,否则更改将不会保存。