我有一个操作 fileStorageFileDownloadAction
,它对两个实体具有几乎相同的逻辑。我不想复制它,而是希望该操作接受当前请求的实体并为其执行逻辑。
该方法检查您是否被允许下载并成功响应所请求的文件。
/**
* @Route("/group/{slug}/profile/filestorage/{groupFile}/download", name="group_profile_filestorage_file_download")
* @ParamConverter("groupFile", class="AppBundle:GroupFile", options={"mapping": {"groupFile": "fileName"}})
*
* @Route("/event/{slug}/profile/filestorage/{eventFile}/download", name="event_profile_filestorage_file_download")
* @ParamConverter("eventFile", class="AppBundle:EventFile", options={"mapping": {"eventFile": "fileName"}})
*/
public function fileStorageFileDownloadAction(?Group $group, ?Event $event, ?GroupFile $groupFile, ?EventFile $eventFile)
{
if ($group && (!$groupFile->getGroup() || $groupFile->getGroup()->getId() != $group->getId())) {
return new NotFoundHttpException();
} elseif ($event && (!$eventFile->getEvent() || $eventFile->getEvent()->getId() != $event->getId())) {
return new NotFoundHttpException();
}
// code for downloading the file
}
如您所见,我必须使用两个不同的 ParamConverters
来获取正确的实体。
groupFile
和eventFile
继承自一个共同的父类file
。但是它们也有我在操作中需要的其他方法,所以我需要正确的子对象。
我不喜欢这个解决方案,因为我觉得它很脏而且不可扩展。如果有一个新的实体类,我也必须扩展参数列表,它会变得更大。
所以我的问题是:这是您在 symfony 中可以做的最好的方法,还是希望有比这种方法更好的方法?
最佳答案
您可以将“下载文件的代码”放入特征(或服务)中。
创建两个操作(groupFileDownloadAction 和 enventFileDownloadAction)并在操作中使用您的特征(或服务)
关于php - 针对不同实体的 Symfony 一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210723/