php - 针对不同实体的 Symfony 一个 Action

标签 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 中可以做的最好的方法,还是希望有比这种方法更好的方法?

最佳答案

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

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

关于php - 针对不同实体的 Symfony 一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210723/

相关文章:

php - Symfony2 chain_provider in_memory 用户登录 "bad credentials"

php - 将 Url 列表转换为 ip?

php - 如何在 PHP 中将字符串转换为符号

forms - Symfony2 : How to add form constraint for a field in bind PRE_SET_DATA depending on the data

mongodb - Doctrine MongoDB ODM 的原子操作

php - Symfony2 中的设计模式 : is EventDispatcher a Mediator or Event Aggregator?

php - 需要有关修复 MySQL 数据库设计和表结构的建议

php - 提高复杂 SQL 查询的性能

php - Mysql用同一表中的另一行值更新一行

php - Doctrine ManyToMany 同一实体重复输入错误