Symfony one action for different entities

Viewed 94

I have one action fileStorageFileDownloadAction which has mostly the same logic for two entities. Instead of copying it, I would like the action to accept the current requested entity and perfom the logic for it.

The method checks if you are allowed to download and on success responses with the requested file.

/**
 * @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
}

As you can see I have to use two different ParamConverters to get the correct entity. groupFile and eventFile are inheriting from a common parent class file. But they have additonal methods too which I need in my action, so I need the correct child object.

I don't like this solution, because I think it is very dirty and not expandable. If there is a new entity class I have to extend the paramterlist as well and it gets even larger.

So my question: is this the best way you can do in symfony or are there hopefully even better ways then this approach?

1 Answers

You can put your "code for downloading the file" into a trait (or a service).

Create two actions (groupFileDownloadAction and enventFileDownloadAction) and use your trait (or service) inside the action

Related