Symfony针对不同实体的一项操作

时间:2018-11-08 15:18:07

标签: php symfony

我有一个动作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来获取正确的实体。 groupFileeventFile继承自公共父类file。但是它们也有我需要的其他方法,因此我需要正确的子对象。

我不喜欢这种解决方案,因为我认为它很脏且无法扩展。如果有一个新的实体类,我也必须扩展参数列表,它会变得更大。

所以我的问题是:这是您可以在symfony中做的最好方法,还是希望有比该方法更好的方法?

1 个答案:

答案 0 :(得分:0)

您可以将“下载文件的代码”放入特征(或服务)中。

创建两个动作(groupFileDownloadAction和enventFileDownloadAction)并在动作内部使用您的特征(或服务)

相关问题