我有一个控制器,它执行一些与实体相关的文件管理。我希望这个控制器可重复使用:
#[ApiResource(
itemOperations: [
'deleteApiFile' => [
'method' => 'DELETE',
'path' => '/foo/{id}/delete-file',
'read' => false,
'controller' => ApiFileDeleteController::class,
],
],
)]
class Foo { /* ... */ }
#[ApiResource(
itemOperations: [
'deleteApiFile' => [
'method' => 'DELETE',
'path' => '/bar/{id}/delete-file',
'read' => false,
'controller' => ApiFileDeleteController::class,
],
],
)]
class Bar { /* ... */ }
这是控制器:
class ApiFileDeleteController
{
public function __invoke(string $id): void
{
// I have the $id now, how do I determine which entity it belongs to?
//
// Logic in this controller is always the same and always for an entity
$example = $this->em->getRepository($class)->find($id);
// How do I get $class?
}
}
问题: 如何在控制器(或
__construct
)中获取 ApiPlatform 配置?
FooApiFileDeleteController
和一个BarApiFileDeleteController
,但将来如果我想扩展,我需要继续添加控制器,只是为了类名。我宁愿现在努力一点,以后就不用担心这个了。就我而言,我可以使用 DataPersister(或在 ApiPlatform 2.6 中)称为处理器)。不是 100% 我想要的*,但现在就可以了。
class ApiFileUploaderDeleteDataPersister implements ContextAwareDataPersisterInterface
{
public function supports($data, array $context = []): bool
{
return is_a($context['resource_class'], ApiFileUploadInterface::class, true);
}
public function persist($data, array $context = [])
{
return $data;
}
public function remove($data, array $context = [])
{
$this->removeFile($context);
}
}
read: true
很重要(通过省略它)。也不需要控制器:
#[ApiResource(
itemOperations: [
'deleteApiFile' => [
'method' => 'DELETE',
'path' => '/bar/{id}/delete-file', # See: ApiFileUploaderDeleteDataPersister
],
],
)]
class Bar { /* ... */ }
* 这不是我正在寻找的原因是因为它现在是一个“隐藏”文件。控制器在 ApiPlatform 配置中定义,因此很容易找到。这更多的是一个背景步骤。不过还不是最糟糕的。